axios.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
  2. import router from '@/router'
  3. import { ElMessage, ElMessageBox } from 'element-plus'
  4. import { useUserStore } from '@/stores/modules/user'
  5. import emitter from '@/utils/bus'
  6. interface codeMessage {
  7. [key: number]: string
  8. }
  9. // const CODE_MESSAGE: codeMessage = {
  10. // 200: '服务器成功返回请求的数据。',
  11. // 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  12. // 401: '用户没有权限(令牌、用户名、密码错误)。',
  13. // 403: '用户得到授权,但是访问是被禁止的。',
  14. // 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  15. // 406: '请求的格式不可得。',
  16. // 410: '请求的资源被永久删除,且不会再得到的。',
  17. // 422: '当创建一个对象时,发生一个验证错误。',
  18. // 456: 'refreshToken过期',
  19. // 457: 'accessToken过期',
  20. // 500: '服务器发生错误,请检查服务器。',
  21. // 502: '网关错误。',
  22. // 503: '服务不可用,服务器暂时过载或维护。',
  23. // 504: '网关超时。'
  24. // }
  25. const CODE_MESSAGE: codeMessage = {
  26. 200: 'The server successfully returned the requested data.',
  27. 400: 'The request was invalid; the server did not create or modify any data.',
  28. 401: 'Unauthorized: invalid token, username, or password.',
  29. 403: 'Access is forbidden despite valid authentication.',
  30. 404: 'The requested resource does not exist; no action was taken by the server.',
  31. 406: 'The requested format is not available.',
  32. 410: 'The requested resource has been permanently deleted and will not be available again.',
  33. 422: 'A validation error occurred while creating an object.',
  34. 456: 'Refresh token expired.',
  35. 457: 'Access token expired.',
  36. 500: 'An internal server error occurred. Please check the server.',
  37. 502: 'Bad gateway.',
  38. 503: 'Service unavailable: the server is temporarily overloaded or under maintenance.',
  39. 504: 'Gateway timeout.'
  40. };
  41. class HttpAxios {
  42. instance: AxiosInstance
  43. timeout = 30000
  44. cancelTokenArr: Array<any> = []
  45. constructor(config: AxiosRequestConfig) {
  46. this.instance = axios.create(config)
  47. // 设置请求拦截
  48. this.instance.interceptors.request.use(this._requestInterceptors, (error: any) => {
  49. return Promise.reject(error)
  50. })
  51. this.instance.interceptors.response.use(this._responseInterceptors, this._checkResponseError)
  52. }
  53. _requestInterceptors = (config: AxiosRequestConfig) => {
  54. // const _config = { timeout: this.timeout }
  55. // return { ...config, ..._config }
  56. return config
  57. }
  58. /**
  59. * 返回拦截
  60. * @param response
  61. * @returns
  62. */
  63. _responseInterceptors = (response: AxiosResponse) => {
  64. if (response.status === 200) {
  65. if (response.data.code === 401 || response.data.code === 403) {
  66. sessionStorage.clear()
  67. router.push('/login')
  68. const userStore = useUserStore()
  69. userStore.logout()
  70. ElMessage.warning({
  71. message: 'Please log in to use this feature.',
  72. grouping: true
  73. })
  74. emitter.emit('login-out');
  75. } else if (response.data.code !== 200 && response.data.code !== 400 && response.data.code !== 4001 && response.data.code !== 4002 && response.data.code !== 4003) {
  76. ElMessageBox.alert(
  77. response.data?.data?.msg || 'The request failed. Please try again later',
  78. 'Prompt',
  79. { confirmButtonText: 'OK', confirmButtonClass: 'el-button--dark' }
  80. )
  81. }
  82. return response.data
  83. }
  84. return Promise.reject(response)
  85. }
  86. _checkResponseError = (error: any) => {
  87. // ✅ 第一步:如果是用户取消的请求,静默处理 or 特殊处理
  88. if (axios.isCancel(error)) {
  89. return Promise.reject(error) // 通常仍 reject,但上层可选择忽略
  90. }
  91. // ✅ 第二步:超时错误(ECONNABORTED)
  92. if (error.code === 'ECONNABORTED') {
  93. ElMessage.error({
  94. message: 'Request timed out, please try again later!',
  95. grouping: true
  96. })
  97. return Promise.reject(error)
  98. }
  99. // ✅ 第三步:其他真实错误
  100. const status = error.response?.status
  101. const statusText = error.response?.statusText
  102. const message = error.message
  103. ElMessage.error({
  104. message: CODE_MESSAGE[status] || statusText || message,
  105. grouping: true
  106. })
  107. return Promise.reject(error)
  108. }
  109. sendRequest = (url: string, params: any, method = 'post', config?: AxiosRequestConfig) => {
  110. if (!this.instance) return
  111. // TODO show loading if needed
  112. // showFullScreenLoading()
  113. const _method = method.toLowerCase()
  114. if (_method === 'get') {
  115. return this.instance.get(url, { params, ...config })
  116. }
  117. if (_method === 'post') {
  118. return this.instance.post(url, params, {
  119. headers: { 'Content-Type': 'multipart/form-data' },
  120. ...config
  121. })
  122. }
  123. if (_method === 'put') {
  124. return this.instance.put(url, params, config)
  125. }
  126. if (_method === 'delete') {
  127. return this.instance.delete(url, { data: params, ...config })
  128. }
  129. return this.instance.post(url, params, config)
  130. }
  131. get(url: string, params?: object, config?: AxiosRequestConfig) {
  132. return this.sendRequest(url, params, 'get', config)
  133. }
  134. post(url: string, params?: object, config?: AxiosRequestConfig) {
  135. return this.sendRequest(url, params, 'post', config)
  136. }
  137. formdata(url: string, params?: object, config?: AxiosRequestConfig) {
  138. return this.sendRequest(url, params, 'formdata', config)
  139. }
  140. put(url: string, params?: object, config?: AxiosRequestConfig) {
  141. return this.sendRequest(url, params, 'put', config)
  142. }
  143. delete(url: string, params?: any, config?: AxiosRequestConfig) {
  144. return this.sendRequest(url, params, 'delete', config)
  145. }
  146. async clearRequests() {
  147. if (this.cancelTokenArr.length === 0) return
  148. this.cancelTokenArr.forEach((token) => {
  149. token.cancel()
  150. })
  151. this.cancelTokenArr = []
  152. }
  153. }
  154. export default new HttpAxios({})