request.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // if the custom code is not 20000, it is judged as an error.
  51. if (res.code !== 0) {
  52. ElMessage({
  53. message: res.message || 'error',
  54. type: 'error',
  55. duration: 5 * 1000,
  56. })
  57. if (res.code === 403) {
  58. removeToken()
  59. window.location.reload()
  60. }
  61. return Promise.reject(res.message || 'error')
  62. } else {
  63. return res
  64. }
  65. },
  66. error => {
  67. if (error.code === 'ECONNABORTED'
  68. && error.message.indexOf('timeout') > -1) {
  69. error.message = 'Connection Time Out!'
  70. }
  71. ElMessage({
  72. message: error.message,
  73. type: 'error',
  74. duration: 5 * 1000,
  75. })
  76. return Promise.reject(error)
  77. },
  78. )
  79. export default service