1. import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
  2. import { Result } from './types'
  3. import { useUserStore } from '/@/store/modules/user'
  4. class request {
  5. private instance: AxiosInstance
  6. private readonly options: AxiosRequestConfig
  7. constructor(options: AxiosRequestConfig) {
  8. this.options = options
  9. this.instance = axios.create(options)
  10. this.instance.interceptors.request.use(
  11. (config) => {
  12. const token = useUserStore().getToken
  13. if (token) {
  14. config.headers.Authorization = `Bearer ${token}`
  15. }
  16. return config
  17. },
  18. (err) => {
  19. return err
  20. }
  21. )
  22. this.instance.interceptors.response.use(
  23. (res) => {
  24. // 拦截响应的数据
  25. if (res.data.code === 0) {
  26. return res.data.data
  27. }
  28. return res.data
  29. },
  30. (err) => {
  31. return err
  32. }
  33. )
  34. }
  35. request<T = any>(config: AxiosRequestConfig): Promise<T> {
  36. return new Promise((resolve, reject) => {
  37. this.instance
  38. .request<any, AxiosResponse<Result<T>>>(config)
  39. .then((res) => {
  40. resolve((res as unknown) as Promise<T>)
  41. })
  42. .catch((err) => {
  43. reject(err)
  44. })
  45. })
  46. }
  47. get<T = any>(config: AxiosRequestConfig): Promise<T> {
  48. return this.request({ ...config, method: 'GET' })
  49. }
  50. post<T = any>(config: AxiosRequestConfig): Promise<T> {
  51. return this.request({ ...config, method: 'POST' })
  52. }
  53. patch<T = any>(config: AxiosRequestConfig): Promise<T> {
  54. return this.request({ ...config, method: 'PATCH' })
  55. }
  56. delete<T = any>(config: AxiosRequestConfig): Promise<T> {
  57. return this.request({ ...config, method: 'DELETE' })
  58. }
  59. }
  60. export default request

aixos取消请求

main.js

  1. //axios cancel req
  2. window.__axiosPromiseArr = []

utils/axiosReq.js

  1. req.cancelToken = new axios.CancelToken((cancel) => {
  2. //__axiosPromiseArr收集请求地址
  3. window.__axiosPromiseArr.push({
  4. url: req.url,
  5. cancel
  6. })
  7. })

思路就是那__axiosPromiseArr全局变量收集axios的请求url,然后挂载到window上
使用

  1. const cancelReq = () => {
  2. //cancel all req when page switch
  3. if (window.__axiosPromiseArr) {
  4. window.__axiosPromiseArr.forEach((ele, ind) => {
  5. ele.cancel()
  6. delete window.__axiosPromiseArr[ind]
  7. })
  8. }
  9. }

codewhy写法

  1. import axios from 'axios'
  2. import type { AxiosInstance } from 'axios'
  3. //import type { HYRequestInterceptors, HYRequestConfig } from './type'
  4. //---------------------------------------------------------------------------
  5. import type { AxiosRequestConfig, AxiosResponse } from 'axios'
  6. export interface HYRequestInterceptors<T = AxiosResponse> {
  7. requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig
  8. requestInterceptorCatch?: (error: any) => any
  9. responseInterceptor?: (res: T) => T
  10. responseInterceptorCatch?: (error: any) => any
  11. }
  12. export interface HYRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
  13. interceptors?: HYRequestInterceptors<T>
  14. showLoading?: boolean
  15. }
  16. //---------------------------------------------------------------------------
  17. import { ElLoading } from 'element-plus'
  18. import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'
  19. const DEAFULT_LOADING = true
  20. class HYRequest {
  21. instance: AxiosInstance
  22. interceptors?: HYRequestInterceptors
  23. showLoading: boolean
  24. loading?: ILoadingInstance
  25. constructor(config: HYRequestConfig) {
  26. // 创建axios实例
  27. this.instance = axios.create(config)
  28. // 保存基本信息
  29. this.showLoading = config.showLoading ?? DEAFULT_LOADING
  30. this.interceptors = config.interceptors
  31. // 使用拦截器
  32. // 1.从config中取出的拦截器是对应的实例的拦截器
  33. this.instance.interceptors.request.use(
  34. this.interceptors?.requestInterceptor,
  35. this.interceptors?.requestInterceptorCatch
  36. )
  37. this.instance.interceptors.response.use(
  38. this.interceptors?.responseInterceptor,
  39. this.interceptors?.responseInterceptorCatch
  40. )
  41. // 2.添加所有的实例都有的拦截器
  42. this.instance.interceptors.request.use(
  43. (config) => {
  44. if (this.showLoading) {
  45. this.loading = ElLoading.service({
  46. lock: true,
  47. text: '正在请求数据....',
  48. background: 'rgba(0, 0, 0, 0.5)'
  49. })
  50. }
  51. return config
  52. },
  53. (err) => {
  54. return err
  55. }
  56. )
  57. this.instance.interceptors.response.use(
  58. (res) => {
  59. // 将loading移除
  60. this.loading?.close()
  61. const data = res.data
  62. if (data.returnCode === '-1001') {
  63. console.log('请求失败~, 错误信息')
  64. } else {
  65. return data
  66. }
  67. },
  68. (err) => {
  69. // 将loading移除
  70. this.loading?.close()
  71. // 例子: 判断不同的HttpErrorCode显示不同的错误信息
  72. if (err.response.status === 404) {
  73. console.log('404的错误~')
  74. }
  75. return err
  76. }
  77. )
  78. }
  79. request<T = any>(config: HYRequestConfig<T>): Promise<T> {
  80. return new Promise((resolve, reject) => {
  81. // 1.单个请求对请求config的处理
  82. if (config.interceptors?.requestInterceptor) {
  83. config = config.interceptors.requestInterceptor(config)
  84. }
  85. // 2.判断是否需要显示loading
  86. if (config.showLoading === false) {
  87. this.showLoading = config.showLoading
  88. }
  89. this.instance
  90. .request<any, T>(config)
  91. .then((res) => {
  92. // 1.单个请求对数据的处理
  93. if (config.interceptors?.responseInterceptor) {
  94. res = config.interceptors.responseInterceptor(res)
  95. }
  96. // 2.将showLoading设置true, 这样不会影响下一个请求
  97. this.showLoading = DEAFULT_LOADING
  98. // 3.将结果resolve返回出去
  99. resolve(res)
  100. })
  101. .catch((err) => {
  102. // 将showLoading设置true, 这样不会影响下一个请求
  103. this.showLoading = DEAFULT_LOADING
  104. reject(err)
  105. return err
  106. })
  107. })
  108. }
  109. get<T = any>(config: HYRequestConfig<T>): Promise<T> {
  110. return this.request<T>({ ...config, method: 'GET' })
  111. }
  112. post<T = any>(config: HYRequestConfig<T>): Promise<T> {
  113. return this.request<T>({ ...config, method: 'POST' })
  114. }
  115. delete<T = any>(config: HYRequestConfig<T>): Promise<T> {
  116. return this.request<T>({ ...config, method: 'DELETE' })
  117. }
  118. patch<T = any>(config: HYRequestConfig<T>): Promise<T> {
  119. return this.request<T>({ ...config, method: 'PATCH' })
  120. }
  121. }
  122. export default HYRequest

上面代码axios封装的算是很全面了,就是对于ts不熟悉的有点不友好