天波用户运营管理后台系统
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.5KB

  1. /*
  2. * @Date: 2021-12-08 15:59:46
  3. * @LastEditors: JinxChen
  4. * @LastEditTime: 2022-01-12 09:18:37
  5. * @FilePath: \GpsCardAdmin\src\utils\request.js
  6. * @description:
  7. */
  8. import axios from 'axios'
  9. import {
  10. Message
  11. } from 'element-ui'
  12. import store from '@/store'
  13. /* import { getToken } from '@/utils/auth' */
  14. // create an axios instance
  15. const service = axios.create({
  16. baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  17. // withCredentials: true, // send cookies when cross-domain requests
  18. /* timeout: 5000 */ // request timeout
  19. })
  20. // request interceptor
  21. service.interceptors.request.use(
  22. config => {
  23. // do something before request is sent
  24. if (store.getters.token) {
  25. // let each request carry token
  26. // ['X-Token'] is a custom headers key
  27. // please modify it according to the actual situation
  28. config.headers['AuthToken'] = store.getters.token;
  29. }
  30. return config
  31. },
  32. error => {
  33. // do something with request error
  34. console.log(error) // for debug
  35. return Promise.reject(error)
  36. }
  37. )
  38. // response interceptor
  39. service.interceptors.response.use(
  40. /**
  41. * If you want to get http information such as headers or status
  42. * Please return response => response
  43. */
  44. /**
  45. * Determine the request status by custom code
  46. * Here is just an example
  47. * You can also judge the status by HTTP Status Code
  48. */
  49. response => {
  50. const res = response.data
  51. // if the custom code is not 20000, it is judged as an error.
  52. /* if (res.code !== 0) {
  53. Message({
  54. message: res.message || '出错了,请联系管理员!',
  55. type: 'error',
  56. duration: 3 * 1000
  57. })
  58. return Promise.reject(new Error(res.message))
  59. } else */
  60. if (res.code === 106) {
  61. // to re-login
  62. setTimeout(() => {
  63. store.dispatch('user/resetToken').then(() => {
  64. Message({
  65. message: 'token过期,请重新登录',
  66. type: 'error',
  67. duration: 1500
  68. })
  69. location.reload()
  70. })
  71. }, 1500)
  72. return Promise.reject(new Error('token过期,请重新登录'))
  73. } else if (res.code === 0) {
  74. return res
  75. } else {
  76. Message({
  77. message: res.message || '出错了,请联系管理员!',
  78. type: 'error',
  79. duration: 3 * 1000
  80. })
  81. return Promise.reject(new Error(res.message))
  82. }
  83. },
  84. error => {
  85. console.log('err' + error) // for debug
  86. Message({
  87. message: error.message,
  88. type: 'error',
  89. duration: 3 * 1000
  90. })
  91. return Promise.reject(error)
  92. }
  93. )
  94. export default service