当前位置: 首页 > news >正文

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的过程中&#xff0c;由于要存储的状态很大&#xff0c;所以使用到了rockdb作为flink的后端存储&#xff0c;本文就来简单看下rockdb的架构设计 Rockdb设计 Rockdb采用了LSM的结构&#xff0c;它和hbase很像&#xff0c;不过严格的说&#xff0c;基于LS…...

【MyBatis】写了 10 年的代码,我最怕写 MyBatis 这些配置,现在有详解了

在使用 mybatis 过程中&#xff0c;当手写 JavaBean和XML 写的越来越多的时候&#xff0c;就越来越容意出错。这种重复性的工作&#xff0c;我们当然不希望做那么多。 还好&#xff0c; mybatis 为我们提供了强大的代码生成--MybatisGenerator。 通过简单的配置&#xff0c;我们…...

全球地表水数据集JRC Global Surface Water Mapping Layers v1.4

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

Spring过滤器和拦截器的区别

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

HIS医疗项目

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

eclipse启动无法找到类(自定义监听器)

一.报错 二.排查 1.首先检查代码是否有问题 本人报错是找不到监听器&#xff0c;故检查监听器的代码和web.xml文件是否有问题 public class DoorListener implements ServletContextListener 监听器是否继承并实现ServletContextListener中的方法。 web.xml中&#xff1a; &…...

Ubuntu openssh-server 离线安装

经常用到ubunutu 20.04容器&#xff0c;但是没有ssh比较难调试代码&#xff0c;离线环境下安装方法&#xff1a; 安装以下三个软件包&#xff0c;点击openssh下载链接可下载&#xff1a; 1、openssh-client_8.2p1-4_amd64.deb 2、openssh-sftp-server_8.2p1-4_amd64.deb 3、…...

servlet页面以及控制台输出中文乱码

如图&#xff1a; servlet首页面&#xff1a; servlet映射页面&#xff1a; 以及控制台输出打印信息&#xff1a; 以上页面均出现中文乱码 下面依次解决&#xff1a; 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 “商品优化&#xff0c;屏蔽不要内容” 1.2提交到远程仓库 master应该被替换为 Gitee 仓库中默认的分支名称 PS D:\VueProje…...

Spring Boot 项目的常用注解与依赖

工具类 lombok 依赖 可以快速的为类提供 get&#xff0c;set&#xff0c;toString 等方法 <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional> </dependency> My…...

【C++11】多线程库 {thread线程库,mutex互斥锁库,condition_variable条件变量库,atomic原子操作库}

在C11之前&#xff0c;涉及到多线程问题&#xff0c;都是和平台相关的&#xff0c;比如windows和linux下各有自己的接口&#xff0c;这使得代码的可移植性比较差。 //在C98标准下&#xff0c;实现可移植的多线程程序 —— 条件编译 #ifdef _WIN32CreateThread(); //在windows系…...

智能导诊系统:基于机器学习和自然语言处理技术,可快速推荐合适的科室和医生

智能导诊系统是一种基于人工智能技术的新型系统&#xff0c;它能够为医院提供患者服务和管理&#xff0c;提高医院的管理效率和服务水平。 技术架构&#xff1a;springbootredismybatis plusmysqlRocketMQ 以下是智能导诊系统的应用场景和功能特点&#xff1a; 应用场景 1.患…...

如何防止图片抖动

如何防止图片抖动 什么是图片抖动&#xff0c;就是我们加载图片完成之后&#xff0c;图片显示&#xff0c;但是其下方内容会跟着下移&#xff0c;这就造成了图片抖动用户体验不好&#xff0c;我们想即使图片没加载出来&#xff0c;页面上也有一个空白的位置留给图片。 我们要知…...

依赖注入方式

依赖注入方式 思考&#xff1a;向一个类中传递数据的方式有几种&#xff1f; 普通方法&#xff08;set方法&#xff09;构造方法 思考&#xff1a;依赖注入描述了在容器中建立bean与bean之间关系依赖的过程&#xff0c;如果bean运行需要的是数字或字符串呢&#xff1f; 引用类…...

HTML 超链接 a 标签

在 HTML 标签中&#xff0c;a 标签用于定义超链接&#xff0c;作用是从一个页面链接到另一个页面。 在 a 标签中有两个常用的属性&#xff1a; - href 属性&#xff0c;用于指定链接目标的 url 地址&#xff08;必须属性&#xff09;。当为标签应用 href 属性时&#xff0c;…...

【cpolar】Ubuntu本地快速搭建web小游戏网站,公网用户远程访问

&#x1f3a5; 个人主页&#xff1a;深鱼~&#x1f525;收录专栏&#xff1a;cpolar&#x1f304;欢迎 &#x1f44d;点赞✍评论⭐收藏 目录 前言 1. 本地环境服务搭建 2. 局域网测试访问 3. 内网穿透 3.1 ubuntu本地安装cpolar 3.2 创建隧道 3.3 测试公网访问 4. 配置…...

数字化企业需要什么样的数据中心

随着科技的迅猛发展和数字化浪潮的涌现&#xff0c;企业越来越依赖于强大而高效的数据中心来支持其业务运营和创新发展。数字化企业需要一个先进的、灵活可扩展的数据中心来满足不断增长的数据需求、提高业务灵活性和确保安全性。 以下是数字化企业需要考虑的关键因素&#xf…...

el-table固定表头(设置height)出现内容过多时不能滚动问题

主要原因是el-table没有div包裹 解决&#xff1a;加一个div并设置其高度和overflow 我自己的主要代码 <div class"contentTable"><el-tableref"table":data"tableData"striperow-dblclick"onRowDblclick"height"100%&q…...

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…...

装饰模式(Decorator Pattern)重构java邮件发奖系统实战

前言 现在我们有个如下的需求&#xff0c;设计一个邮件发奖的小系统&#xff0c; 需求 1.数据验证 → 2. 敏感信息加密 → 3. 日志记录 → 4. 实际发送邮件 装饰器模式&#xff08;Decorator Pattern&#xff09;允许向一个现有的对象添加新的功能&#xff0c;同时又不改变其…...

云原生核心技术 (7/12): K8s 核心概念白话解读(上):Pod 和 Deployment 究竟是什么?

大家好&#xff0c;欢迎来到《云原生核心技术》系列的第七篇&#xff01; 在上一篇&#xff0c;我们成功地使用 Minikube 或 kind 在自己的电脑上搭建起了一个迷你但功能完备的 Kubernetes 集群。现在&#xff0c;我们就像一个拥有了一块崭新数字土地的农场主&#xff0c;是时…...

Day131 | 灵神 | 回溯算法 | 子集型 子集

Day131 | 灵神 | 回溯算法 | 子集型 子集 78.子集 78. 子集 - 力扣&#xff08;LeetCode&#xff09; 思路&#xff1a; 笔者写过很多次这道题了&#xff0c;不想写题解了&#xff0c;大家看灵神讲解吧 回溯算法套路①子集型回溯【基础算法精讲 14】_哔哩哔哩_bilibili 完…...

mongodb源码分析session执行handleRequest命令find过程

mongo/transport/service_state_machine.cpp已经分析startSession创建ASIOSession过程&#xff0c;并且验证connection是否超过限制ASIOSession和connection是循环接受客户端命令&#xff0c;把数据流转换成Message&#xff0c;状态转变流程是&#xff1a;State::Created 》 St…...

定时器任务——若依源码分析

分析util包下面的工具类schedule utils&#xff1a; ScheduleUtils 是若依中用于与 Quartz 框架交互的工具类&#xff0c;封装了定时任务的 创建、更新、暂停、删除等核心逻辑。 createScheduleJob createScheduleJob 用于将任务注册到 Quartz&#xff0c;先构建任务的 JobD…...

1.3 VSCode安装与环境配置

进入网址Visual Studio Code - Code Editing. Redefined下载.deb文件&#xff0c;然后打开终端&#xff0c;进入下载文件夹&#xff0c;键入命令 sudo dpkg -i code_1.100.3-1748872405_amd64.deb 在终端键入命令code即启动vscode 需要安装插件列表 1.Chinese简化 2.ros …...

Linux云原生安全:零信任架构与机密计算

Linux云原生安全&#xff1a;零信任架构与机密计算 构建坚不可摧的云原生防御体系 引言&#xff1a;云原生安全的范式革命 随着云原生技术的普及&#xff0c;安全边界正在从传统的网络边界向工作负载内部转移。Gartner预测&#xff0c;到2025年&#xff0c;零信任架构将成为超…...

在web-view 加载的本地及远程HTML中调用uniapp的API及网页和vue页面是如何通讯的?

uni-app 中 Web-view 与 Vue 页面的通讯机制详解 一、Web-view 简介 Web-view 是 uni-app 提供的一个重要组件&#xff0c;用于在原生应用中加载 HTML 页面&#xff1a; 支持加载本地 HTML 文件支持加载远程 HTML 页面实现 Web 与原生的双向通讯可用于嵌入第三方网页或 H5 应…...

初探Service服务发现机制

1.Service简介 Service是将运行在一组Pod上的应用程序发布为网络服务的抽象方法。 主要功能&#xff1a;服务发现和负载均衡。 Service类型的包括ClusterIP类型、NodePort类型、LoadBalancer类型、ExternalName类型 2.Endpoints简介 Endpoints是一种Kubernetes资源&#xf…...