import axios from 'axios' import type { CancelTokenStatic, AxiosRequestConfig, AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse, CancelTokenSource } from 'axios' import { useGlobalStore } from '@/stores' import { hasOwn, hasOwnDefault } from '@/utils' import { ElMessage } from 'element-plus' /** * @description: 请求配置 * @param {extendHeaders} {[key: string]: string} 扩展请求头用于不满足默认的 Content-Type、token 请求头的情况 * @param {ignoreLoading} boolean 是否忽略 loading 默认 false * @param {token} boolean 是否携带 token 默认 true * @param {ignoreCR} boolean 是否取消请求 默认 false * @param {ignoreCRMsg} string 取消请求的提示信息 默认 Request canceled * @param {contentType} $ContentType 重新定义 Content-Type 默认 json * @param {baseURL} $baseURL baseURL 默认 horizon * @param {timeout} number 超时时间 默认 10000 * @return {_AxiosRequestConfig} **/ interface _AxiosRequestConfig extends AxiosRequestConfig { extendHeaders?: { [key: string]: string } ignoreLoading?: boolean token?: boolean ignoreCR?: boolean ignoreCRMsg?: string } enum ContentType { html = 'text/html', text = 'text/plain', file = 'multipart/form-data', json = 'application/json', form = 'application/x-www-form-urlencoded', stream = 'application/octet-stream', } interface PendingRequest { url?: string cancel: () => void } const Request: AxiosInstance = axios.create() const CancelToken: CancelTokenStatic = axios.CancelToken const source: CancelTokenSource = CancelToken.source() const pendingRequests: Map<string, PendingRequest> = new Map() const globalStore = useGlobalStore() Request.interceptors.request.use( (config: InternalAxiosRequestConfig) => { globalStore.setGlobalState('loading', !hasOwnDefault(config, 'ignoreLoading', true)) config.baseURL = hasOwnDefault(config, 'baseURL', '/api') config.headers = { ...config.headers, ...{ 'Content-Type': ContentType[hasOwnDefault(config, 'Content-Type', 'json')], }, ...hasOwnDefault(config, 'extendHeaders', {}), } hasOwnDefault(config, 'token', true) && (config.headers.token = globalStore.token) config.data = config.data || {} config.params = config.params || {} config.timeout = hasOwnDefault(config, 'timeout', 10000) config.cancelToken = config.cancelToken || new CancelToken(cancel => { const url = config.url || '' if (!pendingRequests.has(url)) { pendingRequests.set(url, { cancel }) } }) hasOwnDefault(config, 'ignoreCR', false) && config.cancelToken!.promise.catch(reason => { ElMessage.warning(hasOwnDefault(config, 'ignoreCRMsg', 'Request canceled')) throw reason }) console.log(pendingRequests) return config }, (error: AxiosError) => { return Promise.reject(error) } ) Request.interceptors.response.use( (response: AxiosResponse) => { globalStore.setGlobalState('loading', false) return response.data }, (error: AxiosError) => { globalStore.setGlobalState('loading', false) const url = error.config.url || '' const pendingRequest = pendingRequests.get(url) if (pendingRequest) { pendingRequest.cancel() pendingRequests.delete(url) } ElMessage.error(error.message) return Promise.reject(error) } ) export default (config?: _AxiosRequestConfig) => Request(config) 根据代码给出例子,取消请求
时间: 2024-01-06 12:04:45 浏览: 176
可以使用 CancelToken 和 pendingRequests 来取消请求。具体的实现方式如下:
1. 在请求拦截器中,为每个请求设置一个 cancelToken,并将请求信息存储到 pendingRequests 中。
2. 在响应拦截器中,如果请求成功,将该请求从 pendingRequests 中删除。如果请求失败,取消该请求,并从 pendingRequests 中删除。
3. 如果需要取消请求,可以调用 pendingRequests 中存储的 cancel 方法。
示例代码如下:
```
import axios from 'axios';
import { CancelToken } from 'axios';
import { ElMessage } from 'element-plus';
interface PendingRequest {
url?: string;
cancel: () => void;
}
const pendingRequests: Map<string, PendingRequest> = new Map();
const request = axios.create();
request.interceptors.request.use((config) => {
// 为每个请求设置 cancelToken
config.cancelToken = new CancelToken((cancel) => {
const url = config.url || '';
if (!pendingRequests.has(url)) {
pendingRequests.set(url, { cancel });
}
});
// 其他拦截器逻辑
return config;
});
request.interceptors.response.use(
(response) => {
const url = response.config.url || '';
// 请求成功,从 pendingRequests 中删除该请求信息
pendingRequests.delete(url);
return response.data;
},
(error) => {
const url = error.config.url || '';
const pendingRequest = pendingRequests.get(url);
if (pendingRequest) {
// 取消请求,并从 pendingRequests 中删除该请求信息
pendingRequest.cancel();
pendingRequests.delete(url);
}
ElMessage.error(error.message);
return Promise.reject(error);
}
);
export function cancelRequest(url: string) {
const pendingRequest = pendingRequests.get(url);
if (pendingRequest) {
// 调用 cancel 方法取消请求
pendingRequest.cancel();
pendingRequests.delete(url);
}
}
export default request;
```
阅读全文