在请求拦截器、响应拦截器中判断请求是否重复
import axios from "axios";
const request = axios.create();
const manyRequests = new Map()
//请求拦截器
request.interceptors.request.use((config) => {
// 1. 拿到请求url与请求方式判断是否存在
const oldControl = manyRequests.get((config.url as string)+config.method)
if (oldControl) {
oldControl.abort(); // 取消请求
manyRequests.delete((config.url as string)+config.method)
}
// 2. 给请求添加一个 control,并添加到map中
const control = new AbortController();
config.signal = control.signal;
manyRequests.set((config.url as string)+config.method, control)
return config;
});
// 响应拦截器
request.interceptors.response.use(
(response) => {
// 3. 请求成功后从map中删除
manyRequests.delete((response.config.url as string)+response.config.method)
return response.data;
},
(error) => {
return Promise.reject(error);
}
);
export default request;