一、关键部分
一、在封装的request.ts中
- 声明一个 abortController
s
对象用于存储要取消的请求(我用了-s表示复数,多个abortcontroller对象,与下面👇的单个abortController区分)- 封装取消请求的函数cancelRequest, 传入要取消的请求ID ( requestId ) 判断如果在AbortController对象中存在该请求,就可以通过abort来中断
- 在请求拦截器中,如果需要让请求可取消:
- 创建一个新的AbortController对象
- 在AbortController 对象存储这个请求ID,键为请求ID,值为刚创建的 abortController 对象
- 将该 abortController 的 signal 对象存到option的signal对象下
- 请求时发送option
export { request, cancelRequest }
javascript
/**
* 创建一个全局的 AbortController 和 signal 对象, 用于取消请求
*/
let abortControllers: { [key: string]: AbortController } = {};
let signal: AbortSignal | null = null; // 没用到
/**
* 取消当前的请求
*/
const cancelRequest = (requestId: string) => {
if (abortControllers[requestId]) {
abortControllers[requestId].abort();
delete abortControllers[requestId];
}
// if (signal) {
// signal.removeEventListener('abort', () => {});
// signal = null;
// }
};
/**
* token拦截器
*/
request.interceptors.request.use((url: string, options: any) => {
let newOptions = { ...options };
if (options.requestId) {
let abortController = new AbortController();
// 存储当前请求的 AbortController 对象
abortControllers[options.requestId] = abortController;
let signal = abortController.signal;
newOptions.signal = signal;
}
// 其他部分。。。。
return { url, options: newOptions };
});
export { request, cancelRequest };
二、封装调用 request 和 cancelRequest 的 callApi 与 cancelApi
javascript
import qs from 'qs';
import { request, cancelRequest } from './request';
interface IConfig {
requestId?: string;
cancelable?: boolean;
}
export const callApi = (method: string, path: string, params?: any, config: IConfig = {}) => {
const body = ['GET', 'DELETE'].includes(method) ? null : JSON.stringify(params);
const urlpath = method === 'GET' && params ? `${path}?${qs.stringify(params)}` : path;
return request(urlpath, {
method,
body,
requestId: config?.cancelable ? config.requestId : undefined
});
};
export const cancelApi = (requestId: string) => {
cancelRequest(requestId);
};
三、调用请求并配置该请求为可取消
javascript
try {
const res = await callApi('GET', url, undefined,{
cancelable: true,
requestId: 'xxx', //id可随意配置为任意字符串,只要保证唯一并且取消时能对应上就行
}).then((res) => res);
return res;
} catch (error) {
console.error(error);
return {
error: {
message: 'Error occurred while fetching data'
}
};
}
四、在合适的地方取消该请求,注意对应上请求ID requestId
javascript
cancelApi('xxx');
二、完整代码:
api / request.ts
javascript
import { message } from 'antd';
import config from '../config/dev';
import { extend } from 'umi-request';
import { history, useModel } from 'umi';
import { isFormData } from '@/utils/utils';
const API_URL = config.apiBase;
const codeMessage = {
200: '服务器成功返回请求的数据',
201: '新建或修改数据成功',
202: '一个请求已经进入后台排队(异步任务)',
204: '删除数据成功',
400: '请求有误',
401: '用户名或密码错误',
403: '用户得到授权,但是访问是被禁止的',
404: '请求失败,结果不存在',
405: '操作失败',
406: '请求的格式不可得',
410: '请求的资源被永久删除',
422: '操作失败',
500: '服务器发生错误,请检查服务器',
502: '网关错误',
503: '服务不可用,服务器暂时过载或维护',
504: '网关超时'
};
type mapCode = 200 | 201 | 202 | 204 | 400 | 401 | 403 | 404 | 405 | 406 | 410 | 422 | 500 | 502 | 503 | 504;
/**
* 创建一个全局的 AbortController 和 signal 对象, 用于取消请求
*/
let abortControllers: { [key: string]: AbortController } = {};
let signal: AbortSignal | null = null;
/**
* 取消当前的请求
*/
const cancelRequest = (requestId: string) => {
if (abortControllers[requestId]) {
abortControllers[requestId].abort();
delete abortControllers[requestId];
}
// if (signal) {
// signal.removeEventListener('abort', () => {});
// signal = null;
// }
};
/**
* 异常处理程序
*/
const errorHandler = (error: { response: Response; data: any; type: string }): Response | undefined => {
const { response, data } = error;
// if (data?.error) {
// // message.error(data.error.message);
// return data;
// }
if (!response) {
if (error.type === 'AbortError') {
return;
}
if (error.type === 'Timeout') {
message.error('请求超时,请诊断网络后重试');
return;
}
message.error('无法连接服务器');
} else if (response && response.status) {
const errorText = codeMessage[response.status as mapCode] || response.statusText;
message.error(errorText);
}
return response;
};
/**
* 配置request请求时的默认参数
*/
const request = extend({
timeout: 50000,
timeoutMessage: '请求超时,请诊断网络后重试',
prefix: process.env.NODE_ENV === 'development' ? API_URL : '/api',
// prefix: process.env.NODE_ENV === 'development' ? API_URL : 'http://192.168.31.196/api',
errorHandler //默认错误处理
// credentials: 'include', //默认请求是否带上cookie
});
/**
* token拦截器
*/
request.interceptors.request.use((url: string, options: any) => {
let newOptions = { ...options };
if (options.requestId) {
let abortController = new AbortController();
// 存储当前请求的 AbortController 对象
abortControllers[options.requestId] = abortController;
let signal = abortController.signal;
newOptions.signal = signal;
}
const token = localStorage.getItem('token');
if (token) {
newOptions.headers['Authorization'] = token ? `Bearer ${token}` : null;
}
newOptions.headers['Content-Type'] = 'application/json';
if (isFormData(newOptions.body)) {
delete newOptions.headers['Content-Type'];
}
if (options.content_type) {
newOptions.headers['Content-Type'] = options.content_type;
delete newOptions['content_type'];
}
return { url, options: newOptions };
});
request.interceptors.response.use((response: any, options: any) => {
const token = localStorage.getItem('token');
if (response.status === 401 && history.location.pathname === '/login' && options.method === 'POST') {
message.error('用户名或密码错误');
return;
}
if (response.status === 401 || response.status === 403 || (!token && history.location.pathname !== '/login')) {
message.destroy();
message.error('登录已过期,请重新登录');
localStorage.removeItem('token');
history.push('/login');
return;
}
// 截获返回204的响应,由于后端只返回空字符串'',不便于处理,所以我将其转换为'204'返回
if (response.status === 204) {
// message.success(codeMessage[response.status as mapCode]);
return '204';
}
return response;
});
export { request, cancelRequest };
api/index.ts中存放的callApi和cancelApi
javascript
import qs from 'qs';
import { request, cancelRequest } from './request';
import { IConfig } from '@/constants/interface';
export const callApi = (method: string, path: string, params?: any, config: IConfig = {}) => {
const body = ['GET', 'DELETE'].includes(method) ? null : JSON.stringify(params);
const urlpath = method === 'GET' && params ? `${path}?${qs.stringify(params)}` : path;
return request(urlpath, { method, body, requestId: config?.cancelable ? config.requestId : undefined });
};
export const cancelApi = (requestId: string) => {
cancelRequest(requestId);
};
export const uploadApi = (path: string, params?: any) => {
const formData = new FormData();
Object.keys(params).forEach((item) => {
formData.append(item, params[item]);
});
return request(path, {
method: 'POST',
body: formData
});
};
Interface.ts
javascript
export interface IConfig {
requestId?: string;
cancelable?: boolean;
}
map.ts调用callApi
javascript
import { IConfig, IMapSerch, IMapStatistic } from '@/constants/interface';
import { callApi } from '.';
import { API } from './api';
const basePath = '/map_search';
export const mapSearch = async (search: string | undefined, config?: IConfig): Promise<API.IResType<IMapSerch>> => {
try {
const res = await callApi('GET', search ? `${basePath}?search=${search}` : basePath, undefined, config).then((res) => res);
return res;
} catch (error) {
console.error(error);
return {
error: {
message: 'Error occurred while fetching data'
}
};
}
};
页面中pages/map/index.tsx
javascript
import { GaodeMap } from '@antv/l7-maps';
import { useEffect, useState, useRef } from 'react';
import { mapSearch } from '@/api/map';
import { cancelApi } from '@/api';
const id = String(Math.random());
export default function MapManage() {
const [height, setHeight] = useState<number>(window.innerHeight - 38);
const [mapScene, setScene] = useState<Scene>();
useEffect(() => {
let scene = new Scene({
id,
map: new GaodeMap({
center: [89.285302, 44.099382],
pitch: 0,
style: 'normal',
zoom: 12,
plugin: ['AMap.ToolBar'],
WebGLParams: {
preserveDrawingBuffer: true
}
}),
logoVisible: false
});
setScene(scene);
scene.on('loaded', async (a) => {
//@ts-ignore
scene.map.add(new window.AMap.TileLayer.Satellite({ opacity: 0.4, detectRetina: true }));
scene.on('moveend', (_) => handleBounds(scene)); // 地图移动结束后触发,包括平移,以及中心点变化的缩放。如地图有拖拽缓动效果,则在缓动结束后触发
scene.on('zoomend', (_) => handleBounds(scene)); // 缩放停止时触发
// =========加载图层数据==========
const data = await fetchDataResult();
setHeight(window.innerHeight - 38);
});
return () => {
// 页面卸载前取消请求
cancelApi('mapSearch');
// @ts-ignore
scene.layerService?.stopAnimate();
scene.destroy();
};
}, []);
const fetchDataResult = async (query: string | undefined = undefined) => {
const result = await mapSearch(query, {
cancelable: true,
requestId: 'mapSearch'
});
return result;
};
return (
<div>
<div id={id} style={{ height: height }} />
</div>
);
}
三、效果
四、最后说明
前端取消请求只是停止等待服务器的响应,但并不会通知服务器端停止处理请求,如果服务器端不进行处理,仍然可能会继续占用资源并处理请求,所以,为了更有效地处理取消请求,应该在后端/服务器端也进行相应的处理