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);
相关推荐
long31636 分钟前
java 工厂方法设计模式 FactoryMethod
java·开发语言·后端·设计模式
宇寒风暖3 小时前
@(AJAX)
前端·javascript·笔记·学习·ajax
柯南二号4 小时前
MacOS 系统计算机专业好用工具安装
开发语言·lua
神洛华5 小时前
Lua语言程序设计2:函数、输入输出、控制结构
开发语言·lua
java1234_小锋5 小时前
一周学会Matplotlib3 Python 数据可视化-绘制热力图(Heatmap)
开发语言·python·信息可视化·matplotlib·matplotlib3
梁辰兴6 小时前
数据结构:串、数组与广义表
开发语言·数据结构·c··数组·广义表
三体世界7 小时前
Mysql基本使用语句(一)
linux·开发语言·数据库·c++·sql·mysql·主键
etcix7 小时前
wrap cpp variant as dll for c to use
java·c语言·开发语言
Giser探索家7 小时前
低空智航平台技术架构深度解析:如何用AI +空域网格破解黑飞与安全管控难题
大数据·服务器·前端·数据库·人工智能·安全·架构
Websites7 小时前
Hyperf 百度翻译接口实现方案
开发语言·自然语言处理·php·自动翻译