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);
相关推荐
就爱瞎逛10 分钟前
TailWind CSS Intellisense 插件在VSCode 上不生效
前端·css·vscode·tailwind
念九_ysl11 分钟前
Java 使用 OpenHTMLToPDF + Batik 将含 SVG 遮罩的 HTML 转为 PDF 的完整实践
java·开发语言·pdf
柚子81614 分钟前
sibling-index:我用这个画时钟表盘
前端·css
yaoxin52112321 分钟前
124. Java 泛型 - 有界类型参数
java·开发语言
UI设计和前端开发从业者28 分钟前
UI前端大数据处理策略优化:基于云计算的数据存储与计算
前端·ui·云计算
liulilittle41 分钟前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
88号技师1 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
勤奋的知更鸟1 小时前
Java 编程之模板方法模式
java·开发语言·模板方法模式
前端小巷子1 小时前
Web开发中的文件上传
前端·javascript·面试
翻滚吧键盘2 小时前
{{ }}和v-on:click
前端·vue.js