request.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import axios from 'axios'
  2. import { ElMessage } from 'element-plus'
  3. import { getToken, removeToken } from '@/utils/auth'
  4. import { useUserStore } from '@/store/user'
  5. import { pinia } from '@/store'
  6. import { useAppStore } from '@/store/app'
  7. // create an axios instance
  8. const service = axios.create({
  9. baseURL: import.meta.env.VITE_SERVER_API,
  10. withCredentials: true, // send cookies when cross-domain requests
  11. timeout: 50000, // request timeout
  12. })
  13. // request interceptor
  14. service.interceptors.request.use(
  15. config => {
  16. if (!config.headers) {
  17. config.headers = {}
  18. }
  19. const userStore = useUserStore(pinia)
  20. const token = userStore.token || getToken()
  21. if (token) {
  22. config.headers['api-token'] = token
  23. }
  24. const app = useAppStore()
  25. const lang = app.setting.lang
  26. if (lang) {
  27. // console.log('lang', lang)
  28. config.headers['Accept-Language'] = lang
  29. }
  30. return config
  31. },
  32. error => {
  33. // do something with request error
  34. return Promise.reject(error)
  35. },
  36. )
  37. // response interceptor
  38. service.interceptors.response.use(
  39. /**
  40. * If you want to get http information such as headers or status
  41. * Please return response => response
  42. */
  43. /**
  44. * Determine the request status by custom code
  45. * Here is just an example
  46. * You can also judge the status by HTTP Status Code
  47. */
  48. response => {
  49. const res = response.data
  50. // for the endpoint /login-options
  51. // I'm not sure if this is a good idea
  52. if (Array.isArray(res)) {
  53. return res;
  54. }
  55. // if the custom code is not 20000, it is judged as an error.
  56. if (res.code !== 0) {
  57. ElMessage({
  58. message: res.message || 'error',
  59. type: 'error',
  60. duration: 5 * 1000,
  61. })
  62. if (res.code === 403) {
  63. removeToken()
  64. window.location.reload()
  65. }
  66. return Promise.reject(res)
  67. } else {
  68. return res
  69. }
  70. },
  71. error => {
  72. if (error.code === 'ECONNABORTED'
  73. && error.message.indexOf('timeout') > -1) {
  74. error.message = 'Connection Time Out!'
  75. }
  76. ElMessage({
  77. message: error.message,
  78. type: 'error',
  79. duration: 5 * 1000,
  80. })
  81. return Promise.reject(error)
  82. },
  83. )
  84. export default service