axios.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* eslint-disable no-const-assign */
  2. import axios from 'axios'
  3. import router from '../src/router/index'
  4. import { Message } from 'element-ui'
  5. // 构建axios实例
  6. axios.create({
  7. baseURL: process.env.BASE_API,
  8. timeout: 10000
  9. })
  10. axios.interceptors.request.use(config => {
  11. const token = sessionStorage.getItem('token')
  12. if (token) {
  13. config.headers.Authorization = 'Bearer ' + token
  14. }
  15. return config
  16. },
  17. err => {
  18. return Promise.reject(err)
  19. })
  20. axios.interceptors.response.use(
  21. response => {
  22. if (response.data.errcode !== 0 || response.data.errcode === 403) {
  23. if (response.data.errmsg.cmd) {
  24. Message.error(response.data.errmsg.cmd)
  25. return false
  26. }
  27. Message.error(response.data.errmsg)
  28. return false
  29. }
  30. return response
  31. },
  32. error => {
  33. const { status, data } = error.response
  34. console.log(error.response)
  35. if (status === 401) {
  36. Message.error('请重新登录')
  37. router.push('/login')
  38. return false
  39. }
  40. if (status === 400) {
  41. Message.error(data.message || data.errmsg)
  42. return false
  43. }
  44. if (status === 500) {
  45. Message.error('系统错误')
  46. return false
  47. }
  48. return data
  49. }
  50. )
  51. export default axios