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 封装好的。

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何在本地搭建Oracle数据库实现公网环境下通过PLSQL工具进行远程访问

文章目录 前言1. 数据库搭建2. 内网穿透2.1 安装cpolar内网穿透2.2 创建隧道映射 3. 公网远程访问4. 配置固定TCP端口地址4.1 保留一个固定的公网TCP端口地址4.2 配置固定公网TCP端口地址4.3 测试使用固定TCP端口地址远程Oracle 前言 Oracle&#xff0c;是甲骨文公司的一款关系…

文件权限设置(chown、chmod、setfacl、chattr)

文件权限设置&#xff08;chown、chmod、setfacl、chattr&#xff09; chown (change owner)&#xff1a;修改文件属主&#xff08;owner&#xff09;和属组 chown 所有者 文件名 chown 所有者:属组名 文件名案例&#xff1a;chown weblogic:bea /data/info.tar 解释&#xf…

小鸟飞呀飞

欢迎来到程序小院 小鸟飞呀飞 玩法&#xff1a;鼠标控制小鸟飞翔的方向&#xff0c;点击鼠标左键上升&#xff0c;不要让小鸟掉落&#xff0c;从管道中经过&#xff0c;快去飞呀飞哦^^。开始游戏https://www.ormcc.com/play/gameStart/204 html <canvas width"288&quo…

工业4.0时代,烤漆房控制柜如何远程监控?

烤漆房控制柜远程监控方案 一、现状 烤漆房是汽车、机械、家具等工业领域广泛应用的设备&#xff0c;主要用于产品的表面涂装。传统的烤漆房控制柜采用本地控制方式&#xff0c;操作人员在现场进行参数设置和设备控制。这种控制方式需要操作人员需要具备一定的专业知识&#x…

2023-2024华为ICT大赛-计算赛道-广东省省赛初赛-高职组-部分赛题分析【2023.11.18】

2023-2024华为ICT大赛 计算赛道 广东省 省赛 初赛 高职组 部分赛题 分析【2023.11.18】 文章目录 单选题tpcds模式中存在表customer&#xff0c;不能成功删除tpcds模式是&#xff08; &#xff09;以下哪个函数将圆转换成矩形&#xff08; &#xff09;下列哪个选项表示依赖该D…

MAC下MNMP应用程序mysql配置文件my.cnf放在哪里?

最近在测试远古的一段代码,有一段数据库报错代码 [Err] 1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column otp.A.id which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_…

新版Testwell CTC++带来哪些新变化?

Testwell CTC在版本10中引入了新的工具ctcreport来直接从符号和数据文件生成HTML报告。详细的特性描述可以在测试井CTC帮助中找到。在本文档中&#xff0c;描述了与前一代报告相比的改进和变化。 Adaptable Layout可调整布局 您可以选择一个适合于项目结构的布局。布局决定了报…

Qt中的tr函数

2023年11月17日&#xff0c;周五上午 今天在学习Qt时&#xff0c;看到这样一行代码&#xff1a; setWindowTitle(tr("线程")); 于是我产生了几个疑问&#xff1a; 1、什么是tr函数&#xff1f; 2、为什么要写成setWindowTitle(tr("线程"))&#xff0c;…

three.js实现管道漫游

先看效果&#xff1a; <template><div><el-container><el-main><div class"box-card-left"><div id"threejs" style"border: 1px solid red"></div><div class"box-right"><pre s…

xaml自动格式化:各个属性分行放置

快捷键&#xff1a;CtrlKD 设置自己需要的属性&#xff1a;工具->选项->文本编辑器->XAML->Formatting 效果如下&#xff1a;

深度学习YOLO图像视频足球和人体检测 - python opencv 计算机竞赛

文章目录 0 前言1 课题背景2 实现效果3 卷积神经网络4 Yolov5算法5 数据集6 最后 0 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 &#x1f6a9; 深度学习YOLO图像视频足球和人体检测 该项目较为新颖&#xff0c;适合作为竞赛课题方向&#xff0c;学长非…

【用unity实现100个游戏之16】Unity程序化生成随机2D地牢游戏1(附项目源码)

文章目录 先看看最终效果前言随机游走算法使用随机游走算法添加地板瓦片1. 新增TilemapVisualizer&#xff0c;用于可视化地图2. 瓦片素材 不运行执行程序化生成地牢方法1. 先简单重构代码2. 新增Editor脚本RandomDungeonGeneratorEditor 将参数保存到可编辑脚本对象&#xff0…

【前端】yarn install

yarn install yarn install 用于安装项目的所有依赖。 当你刚刚签出项目的代码时&#xff0c;或者当项目中的其他开发者添加了你需要选择的新依赖时&#xff0c;最常使用此方法。 如果你习惯使用 npm&#xff0c;你可能希望使用 --save 或 --save-dev。 这些已被 yarn add 和 …

Java-final

【1】修饰变量&#xff1b; 1.public class Test { 2. //这是一个main方法&#xff0c;是程序的入口&#xff1a; 3. public static void main(String[] args) { 4. //第1种情况&#xff1a; 5. //final修饰一个变量&#xff0c;变量的值不可以改变&#…

ios + vue3 Teleport + inset 兼容性问题

目录 1&#xff0c;问题表现2&#xff0c;解决步骤1&#xff0c;teleport 的问题2&#xff0c;inset 的问题3&#xff0c;teleport 的问题之二 1&#xff0c;问题表现 使用 vue3 的 Teleport 实现的 dialog 弹窗&#xff0c;但是在 ios app 中嵌套的 h5 中无法打开。 直接在io…

【考研数学】正交变换后如果不是标准型怎么办?| 关于二次型标准化的一些思考

文章目录 引言一、回顾二次型的定义是什么&#xff1f;什么叫标准二次型&#xff1f;怎么化为标准型&#xff1f; 二、思考写在最后 引言 前阵子做了下 20 年真题&#xff0c;问题大大的&#xff0c;现在订正到矩阵的第一个大题&#xff0c;是关于二次型正交变换的。和常规不同…

当代职场人做分析,当然要用大数据分析工具

不管是从效率、分析的可用性以及灵活性来看&#xff0c;用大数据分析工具都还板上钉钉的。毕竟大数据分析工具集齐了大数据时代数据分析工具应具备的特点优势。 1、对接ERP&#xff0c;立得100BI报表 点击对接金蝶、用友ERP后&#xff0c;BI系统立即即可取数分析&#xff0c;…

JS基础

javascript基础语言与其他语言大差不差&#xff0c;看代码理解即可。复习笔记 变量与数据类型 变量名要见名知意 变量名可以是字母、下划线、$&#xff0c;还有数字&#xff1b; 但是不能以数字开头小写字母开头&#xff0c; 多个单词&#xff0c;第二个单词首字母大写&#…

控制实体小车cartographer建图

cartographer建图 跑通官方例程 下载官方bag https://storage.googleapis.com/cartographer-public-data/bags/backpack_2d/cartographer_paper_deutsches_museum.bag运行bag roslaunch cartographer_ros demo_backpack_2d.launch bag_filename:${HOME}/workspace/carto_ws…

Swift-day 2

1、数据绑定&#xff0c;改变标题 State private var zoomed: Bool false 属性包装器包装的变量self.title 单向绑定 self.$textInput 双向绑定 传的是数据结构 self.title self.textInput 赋值是String self._titletitle //绑定类型加下划线2、数据绑定&#xff0c;传递结构…