封装umi-request时通过 AbortController 配置取消请求

一、关键部分

一、在封装的request.ts中

  1. 声明一个 abortControllers 对象用于存储要取消的请求(我用了-s表示复数,多个abortcontroller对象,与下面👇的单个abortController区分)
  2. 封装取消请求的函数cancelRequest, 传入要取消的请求ID ( requestId ) 判断如果在AbortController对象中存在该请求,就可以通过abort来中断
  3. 在请求拦截器中,如果需要让请求可取消:
    1. 创建一个新的AbortController对象
    2. 在AbortController 对象存储这个请求ID,键为请求ID,值为刚创建的 abortController 对象
    3. 将该 abortController 的 signal 对象存到option的signal对象下
    4. 请求时发送option
  4. export { request, cancelRequest }
/**
* 创建一个全局的 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

 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);
 };

三、调用请求并配置该请求为可取消

 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

cancelApi(‘xxx’);

二、完整代码:

api / request.ts

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

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

export interface IConfig {
	requestId?: string;
	cancelable?: boolean;
}

map.ts调用callApi

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

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>
);
}

三、效果

在这里插入图片描述

四、最后说明

前端取消请求只是停止等待服务器的响应,但并不会通知服务器端停止处理请求,如果服务器端不进行处理,仍然可能会继续占用资源并处理请求,所以,为了更有效地处理取消请求,应该在后端/服务器端也进行相应的处理

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/582222.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Rust Web开发实战:打造高效稳定的服务端应用

Rust Web开发实战&#xff1a;打造高效稳定的服务端应用 本书将带领您从零开始构建Web应用程序&#xff0c;无论是API、微服务还是单体应用&#xff0c;都将一一涵盖。您将学到如何优雅地对外开放API&#xff0c;如何连接数据库以安全存储数据&#xff0c;以及如何对应用程序进…

Mysql基础(三)DDL之create table语句

一 create table 创表 说明&#xff1a; create table相关语句从功能上进行讲解补充&#xff1a; 前面已经讲解过相关的约束,已进行相关的铺垫声明&#xff1a; 参考价值较少,了解即可 ① 基本语法 思考&#xff1a; 约束加在哪里? ② 创建新表 强调&#xff1a;使…

RCD吸收电路:开关电源高频干扰的有效消除器

开关电源中除了我们常规介绍的差模噪声源和共模噪声源&#xff0c;还存在一些其它的噪声源也应该解决&#xff0c;这些高频噪声源同样会带来电磁兼容问题&#xff0c;因此我们需要关注。这里介绍两种干扰源&#xff0c;一种是MOS管的通断带来的高频振荡噪声&#xff0c;另一种是…

Eclipse C++ 无法debug 问题

环境&#xff1a; ubuntu20.04 Eclipse CDT&#xff08;x86_64) 工程&#xff0c;使用的是默认的CMake Project 现象&#xff1a; 1. 使用Eclipse&#xff0c; 加了断点后&#xff0c;debug 无法停在断点&#xff1b;step over 执行后是从main 直接执行到exit &#xff…

ubuntu24.04 正式放弃VNC

1、ubuntu22.04支持情况 去年9月在22.04中测试发现由于gnome启用Wayland桌面&#xff0c;然而Wayland和vnc兼容不佳&#xff0c;就已经黑屏等问题&#xff0c;当时是vnc和ms-rd(微软远程桌面)两个菜单。 Ubuntu22.04 vnc远程黑屏_ubuntu 远程桌面vnc黑屏-CSDN博客文章浏览阅读…

鸿蒙开发HarmonyOS4.0入门与实践

鸿蒙开发HarmonyOS4.0 配合视频一起食用&#xff0c;效果更佳 课程地址&#xff1a;https://www.bilibili.com/video/BV1Sa4y1Z7B1/ 源码地址&#xff1a;https://gitee.com/szxio/harmonyOS4 准备工作 官网地址 鸿蒙开发者官网&#xff1a;https://developer.huawei.com/con…

u盘量产工具拥有分区功能,它把一个U盘分成数个移动盘,更改U盘介质类型(Fixed 和 Removabe),供大家学习研究参考~

非常受欢迎的u盘量产工具。最新版拥有分区功能&#xff0c;它把一个U盘分成数个移动盘&#xff0c;更改U盘介质类型(Fixed 和 Removabel)。数码之家量产工具官方版不是数据恢复&#xff0c;是对U盘底层硬件信息的恢复(非硬件损坏)&#xff0c;使因为底层硬件信息受损电脑无法识…

【stm32】swjtu西南交大嵌入式实验三 外部中断实验:按键中断

项目源文件&#xff1a;https://download.csdn.net/download/qq_61814350/89222788?spm1001.2014.3001.5501 实验内容&#xff1a; 1、编写程序&#xff0c;设置主程序&#xff1a;跑马灯以 0.2s 的速度旋转&#xff1b;将 KB1 设置为外部中断&#xff0c;下 降沿触发&…

在ubuntu 24.04 上安装vmware workstation 17.5.1

ubuntu安装在新组装的i9 14900机器上&#xff0c;用来学习笨叔的ARM64体系结构编程&#xff0c;也熟悉Linux的用法。但有时候写文档总是不方便&#xff0c;还是需要window来用。因此想在ubuntu 24.04上安装Linux版本的vmware worksation 17.5.1以虚拟机的方式安装windows 11。其…

【软测学习笔记】测试入门Day03

&#x1f31f;博主主页&#xff1a;我是一只海绵派大星 &#x1f4da;专栏分类&#xff1a;软件测试笔记 &#x1f4da;参考教程&#xff1a;黑马教程❤️感谢大家点赞&#x1f44d;收藏⭐评论✍️ 目录 一、缺陷 1、定义 2、缺陷标准 3、缺陷产生的原因 4、缺陷的生命周…

Leetcode—1329. 将矩阵按对角线排序【中等】(unordered_map、priority_queue)

2024每日刷题&#xff08;121&#xff09; Leetcode—1329. 将矩阵按对角线排序 实现代码 class Solution { public:vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {const int m mat.size();const int n mat[0].size();unorder…

指导网友完成一起Linux服务器系统文件删除导致不能启动情况下的数据恢复案例

昨日有网友在微信群发起救助&#xff0c;Linux系统不能启动&#xff0c;使用救援U盘也无法恢复&#xff0c;协助他进行了数据恢复&#xff0c;本文记录了处置过程。 图片为网友提供&#xff0c;照得歪歪扭扭的&#xff0c;将就着看看吧。 一、问题现象 1、报错信息 Linux服…

335GB,台北地区倾斜摄影OSGB数据V0.2版介绍!

前几天发布了台北地区倾斜摄影OSGB数据第一个版本(139GB,台北倾斜摄影OSGB数据V0.1版),虽然数据还是一个半成品&#xff0c;完全没想到热度很高&#xff0c;很多读者对这份数据都有比较浓厚的兴趣&#xff0c;在这里首先感谢各位读者的大力支持与鼓励&#xff0c;给了我持续更新…

Discuz! X系列版本安装包

源码下载地址&#xff1a;Discuz! X系列版本安装包 很多新老站长跟我说要找Discuz! X以前的版本安装包&#xff0c;我们做Discuz! X开发已经十几年了&#xff0c;这些都是官方原版安装包&#xff0c;方便大家使用&#xff08;在官网已经找不到这些版本的安装包了&#xff09; …

NLP发展及其详解

一、RNN(循环神经网络) 在这里附上一个很好的笔记 零基础入门深度学习(5) - 循环神经网络 RNN(循环神经网络)的结构特点在于其循环单元的设计,这种设计允许网络在处理序列数据时保持对之前信息的记忆。下面详细解释RNN的结构: 循环单元:RNN的循环单元是网络的核心,它…

4.Docker本地镜像发布至阿里云仓库、私有仓库、DockerHub

文章目录 0、镜像的生成方法1、本地镜像发布到阿里云仓库2、本地镜像发布到私有仓库3、本地镜像发布到Docker Hub仓库 Docker仓库是集中存放镜像的地方&#xff0c;分为公共仓库和私有仓库。 注册服务器是存放仓库的具体服务器&#xff0c;一个注册服务器上可以有多个仓库&…

Shell脚本入门:编写自动化任务的利器

一、Shell概述 Shell最早产生于20世纪70年代早期的Unix操作系统中。作为一种命令解释器&#xff0c;它位于操作系统的最外层&#xff0c;负责直接与用户进行交互。Shell把用户的输入解释给操作系统&#xff0c;并处理操作系统的输出结果&#xff0c;然后将其反馈给用户。这种交…

你不需要总是在 React 中使用 useState

在我审查的一个拉取请求中&#xff0c;我注意到在许多拉取请求中看到的一种模式。React 组件具有多个 UI 状态&#xff0c;例如 loading、error 和 success。 作者使用了多个 useState 钩子来管理这些状态&#xff0c;这导致代码难以阅读且容易出错&#xff0c;例如&#xff1a…

java案例-读取xml文件

需求 导入依赖 <dependencies><!-- dom4j --><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency> </dependencies>代码 SAXReader saxReade…

九_进程关系1+1-终端设备

在Linux操作系统中&#xff0c;/dev/tty、/dev/tty0和/dev/console是三个特殊的设备文件&#xff0c;它们在终端控制和输入/输出过程中扮演着重要的角色。尽管它们看起来很相似&#xff0c;但实际上它们之间存在一些重要的区别。本文将详细介绍这三个设备文件之间的区别以及它们…
最新文章