import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'import { Result } from './types'import { useUserStore } from '/@/store/modules/user'class request {private instance: AxiosInstanceprivate readonly options: AxiosRequestConfigconstructor(options: AxiosRequestConfig) {this.options = optionsthis.instance = axios.create(options)this.instance.interceptors.request.use((config) => {const token = useUserStore().getTokenif (token) {config.headers.Authorization = `Bearer ${token}`}return config},(err) => {return err})this.instance.interceptors.response.use((res) => {// 拦截响应的数据if (res.data.code === 0) {return res.data.data}return res.data},(err) => {return err})}request<T = any>(config: AxiosRequestConfig): Promise<T> {return new Promise((resolve, reject) => {this.instance.request<any, AxiosResponse<Result<T>>>(config).then((res) => {resolve((res as unknown) as Promise<T>)}).catch((err) => {reject(err)})})}get<T = any>(config: AxiosRequestConfig): Promise<T> {return this.request({ ...config, method: 'GET' })}post<T = any>(config: AxiosRequestConfig): Promise<T> {return this.request({ ...config, method: 'POST' })}patch<T = any>(config: AxiosRequestConfig): Promise<T> {return this.request({ ...config, method: 'PATCH' })}delete<T = any>(config: AxiosRequestConfig): Promise<T> {return this.request({ ...config, method: 'DELETE' })}}export default request
aixos取消请求
main.js
//axios cancel reqwindow.__axiosPromiseArr = []
utils/axiosReq.js
req.cancelToken = new axios.CancelToken((cancel) => {//__axiosPromiseArr收集请求地址window.__axiosPromiseArr.push({url: req.url,cancel})})
思路就是那__axiosPromiseArr全局变量收集axios的请求url,然后挂载到window上
使用
const cancelReq = () => {//cancel all req when page switchif (window.__axiosPromiseArr) {window.__axiosPromiseArr.forEach((ele, ind) => {ele.cancel()delete window.__axiosPromiseArr[ind]})}}
codewhy写法
import axios from 'axios'import type { AxiosInstance } from 'axios'//import type { HYRequestInterceptors, HYRequestConfig } from './type'//---------------------------------------------------------------------------import type { AxiosRequestConfig, AxiosResponse } from 'axios'export interface HYRequestInterceptors<T = AxiosResponse> {requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfigrequestInterceptorCatch?: (error: any) => anyresponseInterceptor?: (res: T) => TresponseInterceptorCatch?: (error: any) => any}export interface HYRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {interceptors?: HYRequestInterceptors<T>showLoading?: boolean}//---------------------------------------------------------------------------import { ElLoading } from 'element-plus'import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'const DEAFULT_LOADING = trueclass HYRequest {instance: AxiosInstanceinterceptors?: HYRequestInterceptorsshowLoading: booleanloading?: ILoadingInstanceconstructor(config: HYRequestConfig) {// 创建axios实例this.instance = axios.create(config)// 保存基本信息this.showLoading = config.showLoading ?? DEAFULT_LOADINGthis.interceptors = config.interceptors// 使用拦截器// 1.从config中取出的拦截器是对应的实例的拦截器this.instance.interceptors.request.use(this.interceptors?.requestInterceptor,this.interceptors?.requestInterceptorCatch)this.instance.interceptors.response.use(this.interceptors?.responseInterceptor,this.interceptors?.responseInterceptorCatch)// 2.添加所有的实例都有的拦截器this.instance.interceptors.request.use((config) => {if (this.showLoading) {this.loading = ElLoading.service({lock: true,text: '正在请求数据....',background: 'rgba(0, 0, 0, 0.5)'})}return config},(err) => {return err})this.instance.interceptors.response.use((res) => {// 将loading移除this.loading?.close()const data = res.dataif (data.returnCode === '-1001') {console.log('请求失败~, 错误信息')} else {return data}},(err) => {// 将loading移除this.loading?.close()// 例子: 判断不同的HttpErrorCode显示不同的错误信息if (err.response.status === 404) {console.log('404的错误~')}return err})}request<T = any>(config: HYRequestConfig<T>): Promise<T> {return new Promise((resolve, reject) => {// 1.单个请求对请求config的处理if (config.interceptors?.requestInterceptor) {config = config.interceptors.requestInterceptor(config)}// 2.判断是否需要显示loadingif (config.showLoading === false) {this.showLoading = config.showLoading}this.instance.request<any, T>(config).then((res) => {// 1.单个请求对数据的处理if (config.interceptors?.responseInterceptor) {res = config.interceptors.responseInterceptor(res)}// 2.将showLoading设置true, 这样不会影响下一个请求this.showLoading = DEAFULT_LOADING// 3.将结果resolve返回出去resolve(res)}).catch((err) => {// 将showLoading设置true, 这样不会影响下一个请求this.showLoading = DEAFULT_LOADINGreject(err)return err})})}get<T = any>(config: HYRequestConfig<T>): Promise<T> {return this.request<T>({ ...config, method: 'GET' })}post<T = any>(config: HYRequestConfig<T>): Promise<T> {return this.request<T>({ ...config, method: 'POST' })}delete<T = any>(config: HYRequestConfig<T>): Promise<T> {return this.request<T>({ ...config, method: 'DELETE' })}patch<T = any>(config: HYRequestConfig<T>): Promise<T> {return this.request<T>({ ...config, method: 'PATCH' })}}export default HYRequest
上面代码axios封装的算是很全面了,就是对于ts不熟悉的有点不友好
