1.使用CancelToken:
class RequestHttp {service: AxiosInstance;public constructor(config: AxiosRequestConfig) {// 实例化axiosthis.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
class RequestHttp {service: AxiosInstance;public constructor(config: AxiosRequestConfig) {// 实例化axiosthis.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);