axios的使用,cancelToken取消请求
get请求
// 为给定 ID 的 user 创建请求
axios.get("/user?ID=12345").then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});
// 上面的请求也可以这样做
axios.get("/user", {params: {ID: 12345,},}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});
// 发送 GET 请求(默认的方法)
axios("/user/12345");
post请求
axios.post("/user", {firstName: "Fred",lastName: "Flintstone",}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});// 发送 POST 请求
axios({method: "post",url: "/user/12345",data: {firstName: "Fred",lastName: "Flintstone",},
});
请求及响应配置
const obj = {url: "/user",method: "get", // default// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URLbaseURL: "https://some-domain.com/api/",// `transformRequest` 允许在向服务器发送前,修改请求数据// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 StreamtransformRequest: [function (data, headers) {// 对 data 进行任意转换处理return data;},],// `transformResponse` 在传递给 then/catch 前,允许修改响应数据transformResponse: [function (data) {// 对 data 进行任意转换处理return data;},],// `headers` 是即将被发送的自定义请求头headers: { "X-Requested-With": "XMLHttpRequest" },// `params` 是即将与请求一起发送的 URL 参数// 必须是一个无格式对象(plain object)或 URLSearchParams 对象params: {ID: 12345,},// `paramsSerializer` 是一个负责 `params` 序列化的函数// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)paramsSerializer: function (params) {return Qs.stringify(params, { arrayFormat: "brackets" });},// `data` 是作为请求主体被发送的数据// 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'// 在没有设置 `transformRequest` 时,必须是以下类型之一:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - 浏览器专属:FormData, File, Blob// - Node 专属: Streamdata: {firstName: "Fred",},// `timeout` 指定请求超时的毫秒数(0 表示无超时时间)// 如果请求话费了超过 `timeout` 的时间,请求将被中断timeout: 1000,// `withCredentials` 表示跨域请求时是否需要使用凭证withCredentials: false, // default// `adapter` 允许自定义处理请求,以使测试更轻松// 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).adapter: function (config) {/* ... */},// `auth` 表示应该使用 HTTP 基础验证,并提供凭据// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头auth: {username: "janedoe",password: "s00pers3cret",},// `responseType` 表示服务器响应的数据类型,// 可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'responseType: "json", // default// `responseEncoding` indicates encoding to use for decoding responses// Note: Ignored for `responseType` of 'stream' or client-side requestsresponseEncoding: "utf8", // default// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称xsrfCookieName: "XSRF-TOKEN", // default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: "X-XSRF-TOKEN", // default// `onUploadProgress` 允许为上传处理进度事件onUploadProgress: function (progressEvent) {// Do whatever you want with the native progress event},// `onDownloadProgress` 允许为下载处理进度事件onDownloadProgress: function (progressEvent) {// 对原生进度事件的处理},// `maxContentLength` 定义允许的响应内容的最大尺寸maxContentLength: 2000,// `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve;// 否则,promise 将被 rejectevalidateStatus: function (status) {return status >= 200 && status < 300; // default},// `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目// 如果设置为0,将不会 follow 任何重定向maxRedirects: 5, // default// `socketPath` defines a UNIX Socket to be used in node.js.// e.g. '/var/run/docker.sock' to send requests to the docker daemon.// Only either `socketPath` or `proxy` can be specified.// If both are specified, `socketPath` is used.socketPath: null, // default// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。//允许像这样配置选项:// `keepAlive` 默认没有启用httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),// 'proxy' 定义代理服务器的主机名称和端口// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据// 这将会设置一个 `Proxy-Authorization` 头,// 覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。proxy: {host: "127.0.0.1",port: 9000,auth: {username: "mikeymike",password: "rapunz3l",},},// `cancelToken` 指定用于取消请求的 cancel token// (查看后面的 Cancellation 这节了解更多)cancelToken: new CancelToken(function (cancel) {}),
};
响应结构
const obj = {// `data` 由服务器提供的响应data: {},// `status` 来自服务器响应的 HTTP 状态码status: 200,// `statusText` 来自服务器响应的 HTTP 状态信息statusText: "OK",// `headers` 服务器响应的头headers: {},// `config` 是为请求提供的配置信息config: {},// 'request'// `request` is the request that generated this response// It is the last ClientRequest instance in node.js (in redirects)// and an XMLHttpRequest instance the browserrequest: {},
};
接受响应参数
axios.get("/user/12345").then(function (response) {console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);
});
拦截器
在请求或响应被 then 或 catch 处理前拦截它们
// 添加请求拦截器
axios.interceptors.request.use(function (config) {// 在发送请求之前做些什么return config;},function (error) {// 对请求错误做些什么return Promise.reject(error);}
);// 添加响应拦截器
axios.interceptors.response.use(function (response) {// 对响应数据做点什么return response;},function (error) {// 对响应错误做点什么return Promise.reject(error);}
);
如果你想在稍后移除拦截器,可以这样:
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
可以为自定义 axios 实例添加拦截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
错误处理
axios.get("/user/12345").catch(function (error) {if (error.response) {// The request was made and the server responded with a status code// that falls out of the range of 2xxconsole.log(error.response.data);console.log(error.response.status);console.log(error.response.headers);} else if (error.request) {// The request was made but no response was received// `error.request` is an instance of XMLHttpRequest in the browser and an instance of// http.ClientRequest in node.jsconsole.log(error.request);} else {// Something happened in setting up the request that triggered an Errorconsole.log("Error", error.message);}console.log(error.config);
});
可以使用 validateStatus 配置选项定义一个自定义 HTTP 状态码的错误范围。
axios.get('/user/12345', {validateStatus: function (status) {return status < 500; // Reject only if the status code is greater than or equal to 500}
})
取消请求cancalToken
<body><button id="btn1">点我获取测试数据</button><button id="btn2">取消请求</button><script>const btn1 = document.getElementById('btn1');const btn2 = document.getElementById('btn2');const { CancelToken, isCancel } = axios //CancelToken能为一次请求‘打标识’let cancel;btn1.onclick = async () => {if(cancel) cancel();//避免多次反复请求axios({url: 'http://localhost:5000/test1?delay=3000',cancelToken: new CancelToken((c) => { //c是一个函数,调用c就可以关闭本次请求cancel = c;})}).then(response => { console.log('成功了', response); },error => {if (isCancel(error)) {//如果进入判断,证明:是用户取消了请求console.log('用户取消了请求,原因是', error.message);} else {console.log('失败了', error);}})}btn2.onclick = () => {cancel("取消这个请求");}</script>
</body>
axios 批量发送请求
<body><button id="btn1">点我获取测试数据</button><script>const btn1 = document.getElementById('btn1');btn1.onclick = async () => {axios.all([axios.get('http://localhost:5000/test1'),axios.get('http://localhost:5000/test2'),axios.get('http://localhost:5000/test3'),]).then(response =>{console.log(response);},error =>{console.log(error);})};</script>
</body>
解释:Axios.all( ) 基于 promise.all( ),所有的都是成功的回调才会返回数据,如果有一个失败的回调,就会走错误信息。此方法会按顺序打印 并发的三个请求的数据,并且如果用了延迟请求也会是原本的顺序,这是 axios 封装好的。
相关文章:
axios的使用,cancelToken取消请求
get请求 // 为给定 ID 的 user 创建请求 axios.get("/user?ID12345").then(function (response) {console.log(response);}).catch(function (error) {console.log(error);}); // 上面的请求也可以这样做 axios.get("/user", {params: {ID: 12345,},}).t…...

Rockdb简介
背景 最近在使用flink的过程中,由于要存储的状态很大,所以使用到了rockdb作为flink的后端存储,本文就来简单看下rockdb的架构设计 Rockdb设计 Rockdb采用了LSM的结构,它和hbase很像,不过严格的说,基于LS…...

【MyBatis】写了 10 年的代码,我最怕写 MyBatis 这些配置,现在有详解了
在使用 mybatis 过程中,当手写 JavaBean和XML 写的越来越多的时候,就越来越容意出错。这种重复性的工作,我们当然不希望做那么多。 还好, mybatis 为我们提供了强大的代码生成--MybatisGenerator。 通过简单的配置,我们…...

全球地表水数据集JRC Global Surface Water Mapping Layers v1.4
简介: JRC Global Surface Water Mapping Layers产品,是利用1984至2020年获取的landsat5、landsat7和landsat8的卫星影像,生成分辨率为30米的一套全球地表水覆盖的地图集。用户可以在全球尺度上按地区回溯某个时间上地表水分的变化情况。产品…...

Spring过滤器和拦截器的区别
📑前言 本文主要Spring过滤器和拦截器的区别的问题,如果有什么需要改进的地方还请大佬指出⛺️ 🎬作者简介:大家好,我是青衿🥇 ☁️博客首页:CSDN主页放风讲故事 🌄每日一句&#x…...

HIS医疗项目
文章目录 医疗项目简介HIS项目介绍HIS架构解析HIS业务流程图HIS项目架构图 HIS组件解析——服务支撑 内存设置为4G或以上部署NGINX服务部署web安装JDK部署Elasticsearch安装ik中文分词器 部署rabbitmq部署MySQL服务安装MySQL服务建库、授权用户导入数据 部署Redis测试Redis 部署…...

eclipse启动无法找到类(自定义监听器)
一.报错 二.排查 1.首先检查代码是否有问题 本人报错是找不到监听器,故检查监听器的代码和web.xml文件是否有问题 public class DoorListener implements ServletContextListener 监听器是否继承并实现ServletContextListener中的方法。 web.xml中: &…...
Ubuntu openssh-server 离线安装
经常用到ubunutu 20.04容器,但是没有ssh比较难调试代码,离线环境下安装方法: 安装以下三个软件包,点击openssh下载链接可下载: 1、openssh-client_8.2p1-4_amd64.deb 2、openssh-sftp-server_8.2p1-4_amd64.deb 3、…...

servlet页面以及控制台输出中文乱码
如图: servlet首页面: servlet映射页面: 以及控制台输出打印信息: 以上页面均出现中文乱码 下面依次解决: 1、首页面中文乱码 检查你的html或者jsp页面中meta字符集 如图设置成utf-8 然后重启一下tomcat 2、servl…...

《向量数据库指南》——TruLens + Milvus Cloud构建RAG深入了解性能
深入了解性能 索引类型 本例中,索引类型对查询速度、token 用量或评估没有明显影响。这可能是因为数据量较小的关系。索引类型对较大语料库可能更重要。 Embedding 模型 text-embedding-ada-002 在准确性(0.72,平均 0.60)和答案相关度(0.82,平均0.62)上优于 MiniLM Embeddin…...
vscode代码上传到gitlab
打开终端 1.1输入一下内容提交到本地仓库 PS D:\VueProject2\mall-admin-web> git add . PS D:\VueProject2\mall-admin-web> git commit -m “商品优化,屏蔽不要内容” 1.2提交到远程仓库 master应该被替换为 Gitee 仓库中默认的分支名称 PS D:\VueProje…...
Spring Boot 项目的常用注解与依赖
工具类 lombok 依赖 可以快速的为类提供 get,set,toString 等方法 <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional> </dependency> My…...

【C++11】多线程库 {thread线程库,mutex互斥锁库,condition_variable条件变量库,atomic原子操作库}
在C11之前,涉及到多线程问题,都是和平台相关的,比如windows和linux下各有自己的接口,这使得代码的可移植性比较差。 //在C98标准下,实现可移植的多线程程序 —— 条件编译 #ifdef _WIN32CreateThread(); //在windows系…...

智能导诊系统:基于机器学习和自然语言处理技术,可快速推荐合适的科室和医生
智能导诊系统是一种基于人工智能技术的新型系统,它能够为医院提供患者服务和管理,提高医院的管理效率和服务水平。 技术架构:springbootredismybatis plusmysqlRocketMQ 以下是智能导诊系统的应用场景和功能特点: 应用场景 1.患…...
如何防止图片抖动
如何防止图片抖动 什么是图片抖动,就是我们加载图片完成之后,图片显示,但是其下方内容会跟着下移,这就造成了图片抖动用户体验不好,我们想即使图片没加载出来,页面上也有一个空白的位置留给图片。 我们要知…...

依赖注入方式
依赖注入方式 思考:向一个类中传递数据的方式有几种? 普通方法(set方法)构造方法 思考:依赖注入描述了在容器中建立bean与bean之间关系依赖的过程,如果bean运行需要的是数字或字符串呢? 引用类…...
HTML 超链接 a 标签
在 HTML 标签中,a 标签用于定义超链接,作用是从一个页面链接到另一个页面。 在 a 标签中有两个常用的属性: - href 属性,用于指定链接目标的 url 地址(必须属性)。当为标签应用 href 属性时,…...

【cpolar】Ubuntu本地快速搭建web小游戏网站,公网用户远程访问
🎥 个人主页:深鱼~🔥收录专栏:cpolar🌄欢迎 👍点赞✍评论⭐收藏 目录 前言 1. 本地环境服务搭建 2. 局域网测试访问 3. 内网穿透 3.1 ubuntu本地安装cpolar 3.2 创建隧道 3.3 测试公网访问 4. 配置…...
数字化企业需要什么样的数据中心
随着科技的迅猛发展和数字化浪潮的涌现,企业越来越依赖于强大而高效的数据中心来支持其业务运营和创新发展。数字化企业需要一个先进的、灵活可扩展的数据中心来满足不断增长的数据需求、提高业务灵活性和确保安全性。 以下是数字化企业需要考虑的关键因素…...

el-table固定表头(设置height)出现内容过多时不能滚动问题
主要原因是el-table没有div包裹 解决:加一个div并设置其高度和overflow 我自己的主要代码 <div class"contentTable"><el-tableref"table":data"tableData"striperow-dblclick"onRowDblclick"height"100%&q…...

工业安全零事故的智能守护者:一体化AI智能安防平台
前言: 通过AI视觉技术,为船厂提供全面的安全监控解决方案,涵盖交通违规检测、起重机轨道安全、非法入侵检测、盗窃防范、安全规范执行监控等多个方面,能够实现对应负责人反馈机制,并最终实现数据的统计报表。提升船厂…...

AI Agent与Agentic AI:原理、应用、挑战与未来展望
文章目录 一、引言二、AI Agent与Agentic AI的兴起2.1 技术契机与生态成熟2.2 Agent的定义与特征2.3 Agent的发展历程 三、AI Agent的核心技术栈解密3.1 感知模块代码示例:使用Python和OpenCV进行图像识别 3.2 认知与决策模块代码示例:使用OpenAI GPT-3进…...

家政维修平台实战20:权限设计
目录 1 获取工人信息2 搭建工人入口3 权限判断总结 目前我们已经搭建好了基础的用户体系,主要是分成几个表,用户表我们是记录用户的基础信息,包括手机、昵称、头像。而工人和员工各有各的表。那么就有一个问题,不同的角色…...

linux arm系统烧录
1、打开瑞芯微程序 2、按住linux arm 的 recover按键 插入电源 3、当瑞芯微检测到有设备 4、松开recover按键 5、选择升级固件 6、点击固件选择本地刷机的linux arm 镜像 7、点击升级 (忘了有没有这步了 估计有) 刷机程序 和 镜像 就不提供了。要刷的时…...
Python爬虫(二):爬虫完整流程
爬虫完整流程详解(7大核心步骤实战技巧) 一、爬虫完整工作流程 以下是爬虫开发的完整流程,我将结合具体技术点和实战经验展开说明: 1. 目标分析与前期准备 网站技术分析: 使用浏览器开发者工具(F12&…...
sqlserver 根据指定字符 解析拼接字符串
DECLARE LotNo NVARCHAR(50)A,B,C DECLARE xml XML ( SELECT <x> REPLACE(LotNo, ,, </x><x>) </x> ) DECLARE ErrorCode NVARCHAR(50) -- 提取 XML 中的值 SELECT value x.value(., VARCHAR(MAX))…...

让AI看见世界:MCP协议与服务器的工作原理
让AI看见世界:MCP协议与服务器的工作原理 MCP(Model Context Protocol)是一种创新的通信协议,旨在让大型语言模型能够安全、高效地与外部资源进行交互。在AI技术快速发展的今天,MCP正成为连接AI与现实世界的重要桥梁。…...
CRMEB 框架中 PHP 上传扩展开发:涵盖本地上传及阿里云 OSS、腾讯云 COS、七牛云
目前已有本地上传、阿里云OSS上传、腾讯云COS上传、七牛云上传扩展 扩展入口文件 文件目录 crmeb\services\upload\Upload.php namespace crmeb\services\upload;use crmeb\basic\BaseManager; use think\facade\Config;/*** Class Upload* package crmeb\services\upload* …...
音视频——I2S 协议详解
I2S 协议详解 I2S (Inter-IC Sound) 协议是一种串行总线协议,专门用于在数字音频设备之间传输数字音频数据。它由飞利浦(Philips)公司开发,以其简单、高效和广泛的兼容性而闻名。 1. 信号线 I2S 协议通常使用三根或四根信号线&a…...

Netty从入门到进阶(二)
二、Netty入门 1. 概述 1.1 Netty是什么 Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. Netty是一个异步的、基于事件驱动的网络应用框架,用于…...