axios.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 {
  6. // showFullScreenLoading,
  7. // tryHideFullScreenLoading
  8. // } from '@monorepo/shared/utils/serviceLoading'
  9. interface codeMessage {
  10. [key: number]: string
  11. }
  12. const CODE_MESSAGE: codeMessage = {
  13. 200: '服务器成功返回请求的数据。',
  14. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  15. 401: '用户没有权限(令牌、用户名、密码错误)。',
  16. 403: '用户得到授权,但是访问是被禁止的。',
  17. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  18. 406: '请求的格式不可得。',
  19. 410: '请求的资源被永久删除,且不会再得到的。',
  20. 422: '当创建一个对象时,发生一个验证错误。',
  21. 456: 'refreshToken过期',
  22. 457: 'accessToken过期',
  23. 500: '服务器发生错误,请检查服务器。',
  24. 502: '网关错误。',
  25. 503: '服务不可用,服务器暂时过载或维护。',
  26. 504: '网关超时。'
  27. }
  28. class HttpAxios {
  29. instance: AxiosInstance
  30. timeout = 30000
  31. cancelTokenArr: Array<any> = []
  32. constructor(config: AxiosRequestConfig) {
  33. this.instance = axios.create(config)
  34. // 设置请求拦截
  35. this.instance.interceptors.request.use(this._requestInterceptors, (error: any) => {
  36. return Promise.reject(error)
  37. })
  38. this.instance.interceptors.response.use(this._responseInterceptors, this._checkResponseError)
  39. }
  40. _requestInterceptors = (config: AxiosRequestConfig) => {
  41. // const _config = { timeout: this.timeout }
  42. // return { ...config, ..._config }
  43. return config
  44. }
  45. /**
  46. * 返回拦截
  47. * @param response
  48. * @returns
  49. */
  50. _responseInterceptors = (response: AxiosResponse) => {
  51. if (response.status === 200) {
  52. if (response.data.code === 401 || response.data.code === 403) {
  53. const userStore = useUserStore()
  54. userStore.logout(false)
  55. router.push('/login')
  56. ElMessage.warning({
  57. message: 'Please log in to use this feature.',
  58. grouping: true
  59. })
  60. } else if (response.data.code !== 200 && response.data.code !== 400) {
  61. ElMessageBox.alert(
  62. response.data?.data?.msg || 'The request failed. Please try again later',
  63. 'Prompt',
  64. { confirmButtonText: 'OK', confirmButtonClass: 'el-button--dark' }
  65. )
  66. }
  67. return response.data
  68. }
  69. return Promise.reject(response)
  70. }
  71. _checkResponseError = (error: any) => {
  72. if (error.code === 'ECONNABORTED') {
  73. ElMessage.error({
  74. message: 'Request timed out, please try again later!!',
  75. grouping: true
  76. })
  77. return Promise.reject(error)
  78. }
  79. const status = error.response?.status
  80. const statusText = error.response?.statusText
  81. const message = error.message
  82. ElMessage.error({
  83. message: CODE_MESSAGE[status] || statusText || message,
  84. grouping: true
  85. })
  86. return Promise.reject(error)
  87. }
  88. sendRequest = (url: string, params: any, method = 'post', config?: AxiosRequestConfig) => {
  89. if (!this.instance) return
  90. // TODO show loading if needed
  91. // showFullScreenLoading()
  92. const _method = method.toLowerCase()
  93. if (_method === 'get') {
  94. return this.instance.get(url, { params, ...config })
  95. }
  96. if (_method === 'post') {
  97. return this.instance.post(url, params, {
  98. headers: { 'Content-Type': 'multipart/form-data' },
  99. ...config
  100. })
  101. }
  102. if (_method === 'put') {
  103. return this.instance.put(url, params, config)
  104. }
  105. if (_method === 'delete') {
  106. return this.instance.delete(url, { data: params, ...config })
  107. }
  108. return this.instance.post(url, params, config)
  109. }
  110. get(url: string, params?: object, config?: AxiosRequestConfig) {
  111. return this.sendRequest(url, params, 'get', config)
  112. }
  113. post(url: string, params?: object, config?: AxiosRequestConfig) {
  114. return this.sendRequest(url, params, 'post', config)
  115. }
  116. formdata(url: string, params?: object, config?: AxiosRequestConfig) {
  117. return this.sendRequest(url, params, 'formdata', config)
  118. }
  119. put(url: string, params?: object, config?: AxiosRequestConfig) {
  120. return this.sendRequest(url, params, 'put', config)
  121. }
  122. delete(url: string, params?: any, config?: AxiosRequestConfig) {
  123. return this.sendRequest(url, params, 'delete', config)
  124. }
  125. async clearRequests() {
  126. if (this.cancelTokenArr.length === 0) return
  127. this.cancelTokenArr.forEach((token) => {
  128. token.cancel()
  129. })
  130. this.cancelTokenArr = []
  131. }
  132. }
  133. export default new HttpAxios({})
  134. // export default new HttpAxios({})