axios 官网速通

前言:参考 AXIOS 中文文档

一 起步

1. 介绍

1.1 Axios 是什么?

Axios 是一个基于 promise 网络请求库,作用于 node.js 和浏览器中。在服务端使用 node.js 的 http 模块, 在客户端 (浏览端) 使用 XMLHttpRequests。

1.2 安装

$ npm install axios
# or
$ yarn add axios
# or
$ pnpm add axios

2. 用例

2.1 发起 GET 请求

const axios = require("axios");// 向给定ID的用户发起请求
axios.get("/user?ID=12345").then(function (response) {// 处理成功情况console.log(response);}).catch(function (error) {// 处理错误情况console.log(error);}).finally(function () {// 总是会执行});// 上述请求等同于如下
axios.get("/user", {params: {ID: 12345,},}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);}).finally(function () {// 总是会执行});// 支持async/await用法
async function getUser() {try {const response = await axios.get("/user?ID=12345");console.log(response);} catch (error) {console.error(error);}
}

2.2 发起 POST 请求

axios.post("/user", {firstName: "Fred",lastName: "Flintstone",}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});

2.3 发起多个并发请求

function getUserAccount() {return axios.get("/user/12345");
}function getUserPermissions() {return axios.get("/user/12345/permissions");
}const [acct, perm] = await Promise.all([getUserAccount(),getUserPermissions(),
]);// ORPromise.all([getUserAccount(), getUserPermissions()]).then(function ([acct,perm,
]) {// ...
});

2.4 将 HTML Form 转换成 JSON 进行请求

const { data } = await axios.post("/user", document.querySelector("#my-form"), {headers: {"Content-Type": "application/json",},
});

3. Forms

3.1 Multipart (multipart/form-data)

const { data } = await axios.post("https://httpbin.org/post",{firstName: "Fred",lastName: "Flintstone",orders: [1, 2, 3],photo: document.querySelector("#fileInput").files,},{headers: {"Content-Type": "multipart/form-data",},}
);

3.2 URL encoded form (application/x-www-form-urlencoded)

const { data } = await axios.post("https://httpbin.org/post",{firstName: "Fred",lastName: "Flintstone",orders: [1, 2, 3],},{headers: {"Content-Type": "application/x-www-form-urlencoded",},}
);

二 Axios API

1. Axios API

可以向 axios 传递相关配置来创建请求,axios(config):

// 发起一个post请求
axios({method: "post",url: "/user/12345",data: {firstName: "Fred",lastName: "Flintstone",},
});

axios(url[, config]):

// 发起一个 GET 请求 (默认请求方式)
axios("/user/12345");

1.1 请求方式别名

为了方便起见,已经为所有支持的请求方法提供了别名:

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

axios.postForm(url[, data[, config]])

axios.putForm(url[, data[, config]])

axios.patchForm(url[, data[, config]])

tips:在使用别名方法时,url、method、data 这些属性都不必在配置中指定。

2. Axios 实例

使用自定义配置新建一个实例,axios.create([config]):

const instance = axios.create({baseURL: "https://some-domain.com/api/",timeout: 1000,headers: { "X-Custom-Header": "foobar" },
});

3. 请求配置

配置选项中只有 url 是必需,method 默认使用 GET 方法:

{// `url` 是用于请求的服务器 URLurl: '/user',// `method` 是创建请求时使用的方法method: 'get', // 默认值// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URLbaseURL: 'https://some-domain.com/api/',// `transformRequest` 允许在向服务器发送前,修改请求数据// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream// 你可以修改请求头。transformRequest: [function (data, headers) {// 对发送的 data 进行任意转换处理return data;}],// `transformResponse` 在传递给 then/catch 前,允许修改响应数据transformResponse: [function (data) {// 对接收的 data 进行任意转换处理return data;}],// 自定义请求头headers: {'X-Requested-With': 'XMLHttpRequest'},// `params` 是与请求一起发送的 URL 参数// 必须是一个简单对象或 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', 'DELETE 和 'PATCH' 请求方法// 在没有设置 `transformRequest` 时,则必须是以下类型之一:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - 浏览器专属: FormData, File, Blob// - Node 专属: Stream, Bufferdata: {firstName: 'Fred'},// 发送请求体数据的可选语法// 请求方式 post// 只有 value 会被发送,key 则不会data: 'Country=Brasil&City=Belo Horizonte',// `timeout` 指定请求超时的毫秒数。// 如果请求时间超过 `timeout` 的值,则请求会被中断timeout: 1000, // 默认值是 `0` (永不超时)// `withCredentials` 表示跨域请求时是否需要使用凭证withCredentials: false, // default// `adapter` 允许自定义处理请求,这使测试更加容易。// 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。adapter: function (config) {/* ... */},// `auth` HTTP Basic Authauth: {username: 'janedoe',password: 's00pers3cret'},// `responseType` 表示浏览器将要响应的数据类型// 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'// 浏览器专属:'blob'responseType: 'json', // 默认值// `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)// 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求// Note: Ignored for `responseType` of 'stream' or client-side requestsresponseEncoding: 'utf8', // 默认值// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称xsrfCookieName: 'XSRF-TOKEN', // 默认值// `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值// `onUploadProgress` 允许为上传处理进度事件// 浏览器专属onUploadProgress: function (progressEvent) {// 处理原生进度事件},// `onDownloadProgress` 允许为下载处理进度事件// 浏览器专属onDownloadProgress: function (progressEvent) {// 处理原生进度事件},// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数maxContentLength: 2000,// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数maxBodyLength: 2000,// `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),// 则promise 将会 resolved,否则是 rejected。validateStatus: function (status) {return status >= 200 && status < 300; // 默认值},// `maxRedirects` 定义了在node.js中要遵循的最大重定向数。// 如果设置为0,则不会进行重定向maxRedirects: 5, // 默认值// `socketPath` 定义了在node.js中使用的UNIX套接字。// e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。// 只能指定 `socketPath` 或 `proxy` 。// 若都指定,这使用 `socketPath` 。socketPath: null, // default// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http// and https requests, respectively, in node.js. This allows options to be added like// `keepAlive` that are not enabled by default.httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),// `proxy` 定义了代理服务器的主机名,端口和协议。// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。// 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。// `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。// 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。// 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`proxy: {protocol: 'https',host: '127.0.0.1',port: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},// see https://axios-http.com/zh/docs/cancellationcancelToken: new CancelToken(function (cancel) {}),// `decompress` indicates whether or not the response body should be decompressed// automatically. If set to `true` will also remove the 'content-encoding' header// from the responses objects of all decompressed responses// - Node only (XHR cannot turn off decompression)decompress: true // 默认值}

4. 响应结构

请求的响应包含以下信息:

{// `data` 由服务器提供的响应data: {},// `status` 来自服务器响应的 HTTP 状态码status: 200,// `statusText` 来自服务器响应的 HTTP 状态信息statusText: 'OK',// `headers` 是服务器响应头// 所有的 header 名称都是小写,而且可以使用方括号语法访问// 例如: `response.headers['content-type']`headers: {},// `config` 是 `axios` 请求的配置信息config: {},// `request` 是生成此响应的请求// 在node.js中它是最后一个ClientRequest实例 (in redirects),// 在浏览器中则是 XMLHttpRequest 实例request: {}
}

当使用 then 时,将接收如下响应:

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

5. 默认配置

可以指定默认配置,它将作用于每个请求。

5.1 全局 axios 默认值

axios.defaults.baseURL = "https://api.example.com";
axios.defaults.headers.common["Authorization"] = AUTH_TOKEN;
axios.defaults.headers.post["Content-Type"] ="application/x-www-form-urlencoded";

5.2 自定义实例默认值

// 创建实例时配置默认值
const instance = axios.create({baseURL: "https://api.example.com",
});// 创建实例后修改默认值
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;

5.3 配置的优先级

配置合并顺序是:在 lib/defaults.js 中默认值 -> 实例的 defaults 属性 -> 请求的 config 参数。后者优先级高于前者。如下:

// 使用库提供的默认配置创建实例
// 此时超时配置的默认值是 `0`
const instance = axios.create();// 重写库的超时默认值
// 现在,所有使用此实例的请求都将等待2.5秒,然后才会超时
instance.defaults.timeout = 2500;// 重写此请求的超时时间,因为该请求需要很长时间
instance.get("/longRequest", {timeout: 5000,
});

6. 拦截器

在请求或响应被 then 或 catch 处理前拦截它们:

// 添加请求拦截器
axios.interceptors.request.use(function (config) {// 在发送请求之前做些什么return config;},function (error) {// 对请求错误做些什么return Promise.reject(error);}
);// 添加响应拦截器
axios.interceptors.response.use(function (response) {// 2xx 范围内的状态码都会触发该函数。// 对响应数据做点什么return response;},function (error) {// 超出 2xx 范围的状态码都会触发该函数。// 对响应错误做点什么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 () {/*...*/
});

7. 错误处理

7.1 基础用法

axios.get("/user/12345").catch(function (error) {if (error.response) {// 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围console.log(error.response.data);console.log(error.response.status);console.log(error.response.headers);} else if (error.request) {// 请求已经成功发起,但没有收到响应// `error.request` 在浏览器中是 XMLHttpRequest 的实例,// 而在node.js中是 http.ClientRequest 的实例console.log(error.request);} else {// 发送请求时出了点问题console.log("Error", error.message);}console.log(error.config);
});

7.2 validateStatus

使用 validateStatus 配置选项,可自定义抛出错误的 HTTP code:

axios.get("/user/12345", {validateStatus: function (status) {return status < 500; // 处理状态码小于500的情况},
});

7.3 toJson

使用 toJSON 可以获取更多关于 HTTP 错误的信息:

axios.get("/user/12345").catch(function (error) {console.log(error.toJSON());
});

8. 取消请求

8.1 AbortController

从 v0.22.0 开始,Axios 支持以 fetch API 方式—— AbortController 取消请求:

const controller = new AbortController();axios.get("/foo/bar", {signal: controller.signal,}).then(function (response) {//...});
// 取消请求
controller.abort();

8.2 CancelToken deprecated

使用 CancelToken.source 工厂方法创建一个 cancel token ,如下所示:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();axios.get("/user/12345", {cancelToken: source.token,}).catch(function (thrown) {if (axios.isCancel(thrown)) {console.log("Request canceled", thrown.message);} else {// 处理错误}});axios.post("/user/12345",{name: "new name",},{cancelToken: source.token,}
);// 取消请求(message 参数是可选的)
source.cancel("Operation canceled by the user.");

可以通过传递一个 executor 函数到 CancelToken 的构造函数来创建一个 cancel token:

const CancelToken = axios.CancelToken;
let cancel;axios.get("/user/12345", {cancelToken: new CancelToken(function executor(c) {// executor 函数接收一个 cancel 函数作为参数cancel = c;}),
});// 取消请求
cancel();

9. 请求体编码

9.1 自动序列化

当请求头中的 content-type 是 application/x-www-form-urlencoded 时,Axios 将自动地将普通对象序列化成 urlencoded 的格式:

const data = {x: 1,arr: [1, 2, 3],arr2: [1, [2], 3],users: [{ name: "Peter", surname: "Griffin" },{ name: "Thomas", surname: "Anderson" },],
};await axios.post("https://postman-echo.com/post", data, {headers: { "content-type": "application/x-www-form-urlencoded" },
});

服务器接收到的数据就像是这样:

  {x: '1','arr[]': [ '1', '2', '3' ],'arr2[0]': '1','arr2[1][0]': '2','arr2[2]': '3','arr3[]': [ '1', '2', '3' ],'users[0][name]': 'Peter','users[0][surname]': 'griffin','users[1][name]': 'Thomas','users[1][surname]': 'Anderson'}

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

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

相关文章

【Java EE初阶十五】网络编程TCP/IP协议(二)

1. 关于TCP 1.1 TCP 的socket api tcp的socket api和U大片的socket api差异很大&#xff0c;但是和前面所讲的文件操作很密切的联系 下面主要讲解两个关键的类&#xff1a; 1、ServerSocket&#xff1a;给服务器使用的类&#xff0c;使用这个类来绑定端口号 2、Socket&#xf…

全网最容易理解的KMP算法讲解

引言 其实网上有很多讲解KMP算法的文章&#xff0c;详略不一&#xff0c;我认为有两点没有解释清楚&#xff1a; 第一点&#xff1a;匹配失败以后&#xff0c;模式串的位移 第二点&#xff1a;next数组的生成算法 希望本篇文章能将KMP算法清晰易懂的拆解开来。 暴力匹配 …

网络同步—帧同步和状态同步解析

概述 同步就是要多个客户端表现效果是一致的&#xff0c;而且对于大多数的游戏&#xff0c;不仅仅要表现一致&#xff0c;还要客户端和服务器的数据也是一致的。所以同步是个网络游戏概念&#xff0c;只有网络游戏才需要同步&#xff0c;而单机游戏是不需要同步的。 帧同步和…

算法-3-基本的数据结构

单双链表 1.单链表双链表如何反转 import java.util.ArrayList; import java.util.List;public class Code01_ReverseList {public static class Node {public int value;public Node next;public Node(int data) {value data;}}public static class DoubleNode {public int…

掘根宝典之C++深复制与浅复制(复制构造函数,默认复制构造函数)

到目前为止我们已经学了构造函数&#xff0c;默认构造函数&#xff0c;析构函数&#xff1a;http://t.csdnimg.cn/EOQxx 转换函数&#xff0c;转换构造函数&#xff1a;http://t.csdnimg.cn/kiHo6 友元函数&#xff1a;http://t.csdnimg.cn/To8Tj 接下来我们来学习一个新函数…

python毕设选题 - 大数据全国疫情数据分析与3D可视化 - python 大数据

文章目录 0 前言1 课题背景2 实现效果3 设计原理4 部分代码5 最后 0 前言 &#x1f525; 这两年开始毕业设计和毕业答辩的要求和难度不断提升&#xff0c;传统的毕设题目缺少创新和亮点&#xff0c;往往达不到毕业答辩的要求&#xff0c;这两年不断有学弟学妹告诉学长自己做的…

关于Http和Https

HTTP&#xff08;超文本传输协议&#xff09;和HTTPS&#xff08;超文本传输安全协议&#xff09;是用于在计算机之间传输数据的协议。它们是互联网上常见的两种通信协议&#xff0c;用于浏览器和服务器之间的数据传输。 HTTP&#xff08;超文本传输协议&#xff09;&#xff1…

2024阿里云云服务器ECS价格表出炉

2024年最新阿里云服务器租用费用优惠价格表&#xff0c;轻量2核2G3M带宽轻量服务器一年61元&#xff0c;折合5元1个月&#xff0c;新老用户同享99元一年服务器&#xff0c;2核4G5M服务器ECS优惠价199元一年&#xff0c;2核4G4M轻量服务器165元一年&#xff0c;2核4G服务器30元3…

【Funny Game】 人生重开模拟器

目录 【Funny Game】 人生重开模拟器&#xff01; 人生重开模拟器&#xff01; 文章所属专区 Funny Game 人生重开模拟器&#xff01; 人生重开模拟器&#xff0c;让你体验从零开始的奇妙人生。在这个充满惊喜和挑战的游戏中&#xff0c;你可以自由选择性别、出生地、家庭背景…

String.format()详细用法

String 类有一个强大的字符串格式化方法 format()。下面是常用的方法总结。 一、占位符类型 String formatted String.format("%s今年%d岁。", "小李", 25); // "小李今年25岁。" 二、字符串和整数格式化 // 将第二个入参拼接到模板中,入参长…

职业性格在求职应聘和跳槽中的作用

性格测试对跳槽者的影响大不大&#xff1f;首先我们要弄清楚两个问题&#xff0c;性格对我们的职业生涯又没有影响&#xff0c;性格测试是什么&#xff0c;职场中有哪些应用&#xff1f;性格可以说从生下来就有了&#xff0c;随着我们的成长&#xff0c;我们的性格也越来越根深…

大模型训练流程(一)预训练

预训练GPU内存分析&#xff1a; GPU占用内存 模型权重 梯度 优化器内存&#xff08;动量估计和梯度方差&#xff09; 中间激活值*batchsize GPU初始化内存 训练流程 &#xff08;选基座 —> 扩词表 —> 采样&切分数据 —> 设置学习参数 —> 训练 —>…

什么是美颜SDK?美颜SDK在短视频平台中的作用探究

在这个以视频为主导的平台上&#xff0c;美颜技术在其中扮演了不可或缺的角色。本文将探讨美颜SDK的本质&#xff0c;以及它在短视频平台中所发挥的作用。 一、什么是美颜SDK&#xff1f; 美颜SDK是一种软件开发工具包&#xff0c;其主要功能是通过算法对图像进行美化处理。…

【教3妹学编程-算法题】人员站位的方案数 II

2哥 : 3妹&#xff0c;今天第一天上班啊&#xff0c;开工大吉~ 3妹&#xff1a;2哥&#xff0c;开工大吉鸭&#xff0c;有没有开工红包&#xff1f; 2哥 : 我们公司比较扣&#xff0c;估计不会发的。 3妹&#xff1a;我们公司估计也一样&#xff0c;不过依然挡不住我打工人的热…

Oracle触发器

触发器 满足特定事件时系统自动执行的命名块。主要用于实现一些比较复杂的完整性需求。 分类 DML触发器&#xff0c;DDL触发器&#xff0c;替代触发器&#xff0c;从数据库事件触发器。 DML触发器&#xff1a;在表上执行DML操作时自动触发。 创建DML触发器。 考虑四个方面&a…

【工具类】vscode ssh 远程免密登录开发

存放代码的机器运行 sshd,使用 vscode 的机器保证可以通过 ssh 登录服务器vscode 机器通过 ssh-keygen 生成 ssh 公私钥对将客户端的 id_rsa.pub 加入到服务器的鉴权队列 cat id_rsa.pub >> authorized_keysvscode 配置即可.ctrlp, remote-ssh: open ssh configuration f…

HarmonyOS router页面跳转

默认启动页面index.ets import router from ohos.router import {BusinessError} from ohos.baseEntry Component struct Index {State message: string Hello World;build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)//添加按钮&am…

【 JS 进阶 】原型对象、面向对象

目标 了解构造函数原型对象的语法特征&#xff0c;掌握 JavaScript 中面向对象编程的实现方式&#xff0c;基于面向对象编程思想实现 DOM 操作的封装。 了解面向对象编程的一般特征掌握基于构造函数原型对象的逻辑封装掌握基于原型对象实现的继承理解何为原型链及其作用能够处理…

Hive使用双重GroupBy解决数据倾斜问题

文章目录 1.数据准备2.双重group by实现 解决数据倾斜2.1 第一层加盐group by2.2 第二层去盐group by 1.数据准备 create table wordcount(a string) row format delimited fields terminated by ‘,’; load data local inpath ‘opt/2.txt’ into table wordcount; hive (…

spring boot rabbitmq常用配置

直接上代码 package com.example.demo;import org.aopalliance.aop.Advice; import org.springframework.amqp.rabbit.annotation.RabbitListenerConfigurer; import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; import org.springframewo…