request.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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: window.Domain.api_url, // url = base url + request url
  8. // withCredentials: true, // send cookies when cross-domain requests
  9. timeout: 10000 // 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['Authorization'] = `Bearer ${getToken()}`
  20. }
  21. return config
  22. },
  23. error => {
  24. // do something with request error
  25. console.log(error) // for debug
  26. return Promise.reject(error)
  27. }
  28. )
  29. // response interceptor
  30. service.interceptors.response.use(
  31. /**
  32. * If you want to get http information such as headers or status
  33. * Please return response => response
  34. */
  35. /**
  36. * Determine the request status by custom code
  37. * Here is just an example
  38. * You can also judge the status by HTTP Status Code
  39. */
  40. response => {
  41. // if the custom code is not 20000, it is judged as an error.
  42. if (!response.headers['content-type'].includes('application/json')) {
  43. return response
  44. }
  45. // application/json
  46. const { msg, code = 'Error' } = response.data
  47. if (code !== 200) {
  48. if (code === 403) {
  49. Message({
  50. message: 'Insufficient permissions, please contact your administrator',
  51. type: 'error',
  52. duration: 5 * 1000
  53. })
  54. } else if (code === 401) {
  55. MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
  56. confirmButtonText: 'Re-Login',
  57. cancelButtonText: 'Cancel',
  58. type: 'warning'
  59. }).then(() => {
  60. store.dispatch('user/resetToken').then(() => {
  61. location.reload()
  62. })
  63. })
  64. } else {
  65. Message({
  66. message: msg,
  67. type: 'error',
  68. duration: 5 * 1000
  69. })
  70. }
  71. return Promise.reject(new Error(msg))
  72. }
  73. return response.data
  74. },
  75. error => {
  76. console.log(error)
  77. Message({
  78. message: error.message,
  79. type: 'error',
  80. duration: 5 * 1000
  81. })
  82. return Promise.reject(error)
  83. }
  84. )
  85. export default service