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);
相关推荐
是发财不是旺财2 分钟前
跟着deepseek学golang--认识golang
开发语言·后端·golang
Apifox.4 分钟前
Apifox 4月更新|Apifox在线文档支持LLMs.txt、评论支持使用@提及成员、支持为团队配置「IP 允许访问名单」
前端·人工智能·后端·ai·ai编程
划水不带桨10 分钟前
大数据去重
前端
沉迷...15 分钟前
手动实现legend 与 echarts图交互 通过js事件实现图标某项的高亮 显示与隐藏
前端·javascript·echarts
可观测性用观测云30 分钟前
观测云数据在Grafana展示的最佳实践
前端
Bruce_Liuxiaowei37 分钟前
基于Python+Flask的MCP SDK响应式文档展示系统设计与实现
开发语言·python·flask·mcp
chuxinweihui44 分钟前
数据结构——栈与队列
c语言·开发语言·数据结构·学习·算法·链表
我不是程序猿儿44 分钟前
[C#]反射的实战应用,实际数据模拟
开发语言·c#
uwvwko1 小时前
ctfhow——web入门214~218(时间盲注开始)
前端·数据库·mysql·ctf
Json____1 小时前
使用vue2开发一个医疗预约挂号平台-前端静态网站项目练习
前端·vue2·网站模板·静态网站·项目练习·挂号系统