request.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import axios from 'axios'
  2. import { MessageBox, Message } from 'element-ui'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. // create an axios instance
  6. const service = axios.create({
  7. baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  8. // withCredentials: true, // send cookies when cross-domain requests
  9. timeout: 5000 // request timeout
  10. })
  11. // request interceptor
  12. service.interceptors.request.use(
  13. config => {
  14. // do something before request is sent
  15. if (store.getters.token) {
  16. // let each request carry token
  17. // ['X-Token'] is a custom headers key
  18. // please modify it according to the actual situation
  19. config.headers['X-Token'] = getToken()
  20. config.headers['Authorization'] = getToken()
  21. }
  22. return config
  23. },
  24. error => {
  25. // do something with request error
  26. console.log(error) // for debug
  27. return Promise.reject(error)
  28. }
  29. )
  30. // response interceptor
  31. service.interceptors.response.use(
  32. /**
  33. * If you want to get http information such as headers or status
  34. * Please return response => response
  35. */
  36. /**
  37. * Determine the request status by custom code
  38. * Here is just an example
  39. * You can also judge the status by HTTP Status Code
  40. */
  41. response => {
  42. return response
  43. // const res = response.data
  44. //
  45. // // if the custom code is not 20000, it is judged as an error.
  46. // if (res.code !== 20000) {
  47. // Message({
  48. // message: res.message || 'Error',
  49. // type: 'error',
  50. // duration: 5 * 1000
  51. // })
  52. //
  53. // // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  54. // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  55. // // to re-login
  56. // MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
  57. // confirmButtonText: 'Re-Login',
  58. // cancelButtonText: 'Cancel',
  59. // type: 'warning'
  60. // }).then(() => {
  61. // store.dispatch('user/resetToken').then(() => {
  62. // location.reload()
  63. // })
  64. // })
  65. // }
  66. // return Promise.reject(new Error(res.message || 'Error'))
  67. // } else {
  68. // return res
  69. // }
  70. },
  71. error => {
  72. // 自行处理400+ 服务端定义的异常
  73. if (error.response.status < 400 || error.response.status >= 500) {
  74. Message({
  75. message: error.message,
  76. type: 'error',
  77. duration: 5 * 1000
  78. })
  79. }
  80. return Promise.reject(error)
  81. }
  82. )
  83. export default service