84 lines
2.7 KiB
JavaScript
84 lines
2.7 KiB
JavaScript
|
import axios from 'axios'; // 导入axios库
|
||
|
|
||
|
// 自定义请求类
|
||
|
class Request {
|
||
|
constructor(config) {
|
||
|
this.instance = axios.create(config); // 创建axios实例
|
||
|
this.abortControllerMap = new Map(); // 存储请求的AbortController
|
||
|
this.interceptorsObj = config.interceptors; // 存储拦截器对象
|
||
|
|
||
|
// 默认请求拦截器
|
||
|
this.instance.interceptors.request.use(
|
||
|
(res) => {
|
||
|
const controller = new AbortController(); // 创建新的AbortController
|
||
|
const url = res.url || ''; // 获取请求的URL
|
||
|
res.signal = controller.signal; // 将信号绑定到请求
|
||
|
this.abortControllerMap.set(url, controller); // 存储控制器
|
||
|
return res; // 返回请求配置
|
||
|
},
|
||
|
(err) => Promise.reject(err) // 处理请求错误
|
||
|
);
|
||
|
|
||
|
// 自定义请求拦截器
|
||
|
this.instance.interceptors.request.use(
|
||
|
this.interceptorsObj?.requestInterceptors,
|
||
|
this.interceptorsObj?.requestInterceptorsCatch
|
||
|
);
|
||
|
|
||
|
// 自定义响应拦截器
|
||
|
this.instance.interceptors.response.use(
|
||
|
this.interceptorsObj?.responseInterceptors,
|
||
|
this.interceptorsObj?.responseInterceptorsCatch
|
||
|
);
|
||
|
|
||
|
// 默认响应拦截器
|
||
|
this.instance.interceptors.response.use(
|
||
|
(res) => {
|
||
|
const url = res.config.url || ''; // 获取响应的URL
|
||
|
this.abortControllerMap.delete(url); // 删除已完成请求的控制器
|
||
|
return res.data; // 返回响应数据
|
||
|
},
|
||
|
(err) => Promise.reject(err) // 处理响应错误
|
||
|
);
|
||
|
}
|
||
|
|
||
|
// 发送请求的方法
|
||
|
request(config) {
|
||
|
return new Promise((resolve, reject) => {
|
||
|
// 如果有自定义请求拦截器,先执行
|
||
|
if (config.interceptors?.requestInterceptors) {
|
||
|
config = config.interceptors.requestInterceptors(config);
|
||
|
}
|
||
|
// 发送请求
|
||
|
this.instance
|
||
|
.request(config)
|
||
|
.then((res) => {
|
||
|
// 如果有自定义响应拦截器,先执行
|
||
|
if (config.interceptors?.responseInterceptors) {
|
||
|
res = config.interceptors.responseInterceptors(res);
|
||
|
}
|
||
|
resolve(res); // 解析响应
|
||
|
})
|
||
|
.catch(reject); // 捕获错误
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// 取消所有请求的方法
|
||
|
cancelAllRequest() {
|
||
|
for (const [, controller] of this.abortControllerMap) {
|
||
|
controller.abort(); // 取消请求
|
||
|
}
|
||
|
this.abortControllerMap.clear(); // 清空控制器映射
|
||
|
}
|
||
|
|
||
|
// 取消特定请求的方法
|
||
|
cancelRequest(url) {
|
||
|
const urlList = Array.isArray(url) ? url : [url]; // 确保url是数组
|
||
|
for (const _url of urlList) {
|
||
|
this.abortControllerMap.get(_url)?.abort(); // 取消请求
|
||
|
this.abortControllerMap.delete(_url); // 删除控制器
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export default Request; // 导出自定义请求类
|