axios取消请求

1.使用CancelToken:

TypeScript 复制代码
class RequestHttp {
	service: AxiosInstance;
	public constructor(config: AxiosRequestConfig) {
		// 实例化axios
		this.service = axios.create(config);

		/**
		 * @description 请求拦截器
		 * 客户端发送请求 -> [请求拦截器] -> 服务器
		 */
		this.service.interceptors.request.use(
			(config: any) => {
				if (!getUrlParams("id")) {
					config["cancelToken"] = new axios.CancelToken(function (cancel) {
						cancel("当前URL中未携带id参数,请求已被取消");
					});
				}
				return config;
			},
			(error: AxiosError) => {
				return Promise.reject(error);
			}
		);
	}
}

export default new RequestHttp(config);

2.使用AbortController

javascript 复制代码
class RequestHttp {
	service: AxiosInstance;
	public constructor(config: AxiosRequestConfig) {
		// 实例化axios
		this.service = axios.create(config);

		/**
		 * @description 请求拦截器
		 * 客户端发送请求 -> [请求拦截器] -> 服务器
		 */
		this.service.interceptors.request.use(
			(config: any) => {
				if (!getUrlParams("id")) {
					const abortController = new AbortController();
					config.signal = abortController.signal;
					abortController.abort("当前URL中未携带id参数,请求已被取消");
				}
				return config;
			},
			(error: AxiosError) => {
				return Promise.reject(error);
			}
		);
	}
}

export default new RequestHttp(config);
相关推荐
wearegogog1233 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
molaifeng3 小时前
Go 语言如何实现高性能网络 I/O:Netpoller 模型揭秘
开发语言·网络·golang
Drawing stars3 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
崇山峻岭之间3 小时前
Matlab学习记录33
开发语言·学习·matlab
品克缤3 小时前
Element UI MessageBox 增加第三个按钮(DOM Hack 方案)
前端·javascript·vue.js
Evand J3 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
小二·3 小时前
Python Web 开发进阶实战:性能压测与调优 —— Locust + Prometheus + Grafana 构建高并发可观测系统
前端·python·prometheus
小沐°3 小时前
vue-设置不同环境的打包和运行
前端·javascript·vue.js
jllllyuz3 小时前
基于MATLAB的二维波场模拟程序(含PML边界条件)
开发语言·matlab
忆锦紫4 小时前
图像增强算法:Gamma映射算法及MATLAB实现
开发语言·算法·matlab