axios.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. class HttpAxios {
  26. instance: AxiosInstance
  27. timeout = 30000
  28. cancelTokenArr: Array<any> = []
  29. constructor(config: AxiosRequestConfig) {
  30. this.instance = axios.create(config)
  31. // 设置请求拦截
  32. this.instance.interceptors.request.use(this._requestInterceptors, (error: any) => {
  33. return Promise.reject(error)
  34. })
  35. this.instance.interceptors.response.use(this._responseInterceptors, this._checkResponseError)
  36. }
  37. _requestInterceptors = (config: AxiosRequestConfig) => {
  38. // const _config = { timeout: this.timeout }
  39. // return { ...config, ..._config }
  40. return config
  41. }
  42. /**
  43. * 返回拦截
  44. * @param response
  45. * @returns
  46. */
  47. _responseInterceptors = (response: AxiosResponse) => {
  48. if (response.status === 200) {
  49. if (response.data.code === 401 || response.data.code === 403) {
  50. sessionStorage.clear()
  51. router.push('/login')
  52. const userStore = useUserStore()
  53. userStore.logout()
  54. ElMessage.warning({
  55. message: 'Please log in to use this feature.',
  56. grouping: true
  57. })
  58. emitter.emit('login-out');
  59. } else if (response.data.code !== 200 && response.data.code !== 400) {
  60. ElMessageBox.alert(
  61. response.data?.data?.msg || 'The request failed. Please try again later',
  62. 'Prompt',
  63. { confirmButtonText: 'OK', confirmButtonClass: 'el-button--dark' }
  64. )
  65. }
  66. return response.data
  67. }
  68. return Promise.reject(response)
  69. }
  70. _checkResponseError = (error: any) => {
  71. if (error.code === 'ECONNABORTED') {
  72. ElMessage.error({
  73. message: 'Request timed out, please try again later!!',
  74. grouping: true
  75. })
  76. return Promise.reject(error)
  77. }
  78. const status = error.response?.status
  79. const statusText = error.response?.statusText
  80. const message = error.message
  81. ElMessage.error({
  82. message: CODE_MESSAGE[status] || statusText || message,
  83. grouping: true
  84. })
  85. return Promise.reject(error)
  86. }
  87. sendRequest = (url: string, params: any, method = 'post', config?: AxiosRequestConfig) => {
  88. if (!this.instance) return
  89. // TODO show loading if needed
  90. // showFullScreenLoading()
  91. const _method = method.toLowerCase()
  92. if (_method === 'get') {
  93. return this.instance.get(url, { params, ...config })
  94. }
  95. if (_method === 'post') {
  96. return this.instance.post(url, params, {
  97. headers: { 'Content-Type': 'multipart/form-data' },
  98. ...config
  99. })
  100. }
  101. if (_method === 'put') {
  102. return this.instance.put(url, params, config)
  103. }
  104. if (_method === 'delete') {
  105. return this.instance.delete(url, { data: params, ...config })
  106. }
  107. return this.instance.post(url, params, config)
  108. }
  109. get(url: string, params?: object, config?: AxiosRequestConfig) {
  110. return this.sendRequest(url, params, 'get', config)
  111. }
  112. post(url: string, params?: object, config?: AxiosRequestConfig) {
  113. return this.sendRequest(url, params, 'post', config)
  114. }
  115. formdata(url: string, params?: object, config?: AxiosRequestConfig) {
  116. return this.sendRequest(url, params, 'formdata', config)
  117. }
  118. put(url: string, params?: object, config?: AxiosRequestConfig) {
  119. return this.sendRequest(url, params, 'put', config)
  120. }
  121. delete(url: string, params?: any, config?: AxiosRequestConfig) {
  122. return this.sendRequest(url, params, 'delete', config)
  123. }
  124. async clearRequests() {
  125. if (this.cancelTokenArr.length === 0) return
  126. this.cancelTokenArr.forEach((token) => {
  127. token.cancel()
  128. })
  129. this.cancelTokenArr = []
  130. }
  131. }
  132. export default new HttpAxios({})