文章目录

  • 1. 引言
    • 1.1 Axios 介绍
    • 1.2 Httpbin 介绍
  • 2. 开始使用
    • 2.1 安装并引入
      • 2.1.1 使用nodejs引入
      • 2.1.2 在浏览器中引入
    • 2.2 发送get请求
    • 2.3 发送post请求
      • 2.3.1 application/json
      • 2.3.2 application/x-www-form-urlencoded
      • 2.3.3 multipart/form-data
    • 2.4 上传文件
      • 2.4.1 利用FormData对象
      • 2.4.2 直接上传二进制文件
  • 3. 参数详解
    • 3.1 函数别名
      • 3.1.1 主要方法
      • 3.1.2 别名方法
      • 3.1.3 使用示例
    • 3.2 request config 参数
    • 3.3 response 参数
    • 3.4 error 参数
    • 3.5 Axios对象
  • 4. 拦截器
    • 4.1 拦截器简介
    • 4.2 请求拦截器
    • 4.3 响应拦截器
  • 4.4 移除拦截器
  • 5. 参考资料

1. 引言

1.1 Axios 介绍

Axios 是一个基于 promise 网络请求库,使用 Axios 可以将同样的网络请求代码用于node.js 和 浏览器 中。同时,Axios 也是 Vue 官方推荐的网络请求库

1.2 Httpbin 介绍

Httpbin 是一个 HTTP 请求测试网站,我们可以利用 Httpbin 做一些网络请求的练习和测试。在本篇博客中,我们将使用 Axios 向 Httpbin 发送网络请求。

2. 开始使用

2.1 安装并引入

2.1.1 使用nodejs引入

  1. 安装:
# 使用npm
npm install axios --save# 或使用yarn
yarn add axios
  1. 使用:
// 使用CommonJS语法引入
import axios from "axios";// 向Httpbin发出get请求
axios.get("http://httpbin.org/get").then(res => {console.log(res.data);
});

输出:

{args: {},headers: {Accept: 'application/json, text/plain, */*',Host: 'httpbin.org','User-Agent': 'axios/0.26.1','X-Amzn-Trace-Id': ''},origin: '0.0.0.',url: 'http://httpbin.org/get'
}

2.1.2 在浏览器中引入

  1. 利用CDN引入:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  1. 使用:
// 向Httpbin发出get请求
axios.get("http://httpbin.org/get").then(res => {alert(JSON.stringify(res.data));
});

输出:

{args: {},headers: {Accept: 'application/json, text/plain, */*',Host: 'httpbin.org','User-Agent': 'axios/0.26.1','X-Amzn-Trace-Id': ''},origin: '0.0.0.',url: 'http://httpbin.org/get'
}

2.2 发送get请求

let query_string = {name: "xiaoming",age: "18"
};axios.request({url: "http://httpbin.org/get", // 请求urlmethod: "get",       // 请求方式params: query_string // Http请求中的query string
}).then(res => {console.log(res.data);
});

HTTP中的 Query string 会被拼接在 url 后面进行发送,所以上面代码中发出的实际请求 url 是 http://httpbin.org/get?name=xiaoming&age=18

2.3 发送post请求

2.3.1 application/json

Axios默认的post请求格式就是 application/json,可以直接发送:

let post_data = {name: "xiaoming",age: "18"
};axios.request({url: "http://httpbin.org/post", // 请求urlmethod: "post",                 // 请求类型data: post_data                 // 请求体
}).then(res => {console.log(res.data);
});

2.3.2 application/x-www-form-urlencoded

Axios 发送application/x-www-form-urlencoded 格式的请求体需要将JSON数据{"name: "xiaoming", "age": "18"} 序列化为查询字符格式 name=xiaoming&age=18,Axios会自动识别请求体的格式并在请求头中声明。

  1. 在nodejs中可以使用 qs 库进行序列化
const axios = require("axios");
const qs = require("qs");let post_data = {name: "xiaoming",age: "18"
};post_data = qs.stringify(post_data);axios.request({url: "http://httpbin.org/post",method: "post",data: post_data
}).then(res => {console.log(res.data);
});
  1. 浏览器中可以使用 URLSearchParams API
let post_data = new URLSearchParams();post_data.append('name', 'xiaoming');
post_data.append('age', '18');axios.request({url: "http://httpbin.org/post",method: "post",data: post_data
}).then(res => {console.log(res.data);
});

2.3.3 multipart/form-data

Axios 发送multipart/form-data 格式的请求体需要将数据变成 FormData 对象格式,Axios 会自动识别请求体的格式并在请求头中声明。

  1. 在nodejs中可以使用 form-data
const axios = require("axios");
const FormData = require('form-data');let post_data = new FormData();
post_data.append('name', 'xiaoming');
post_data.append('age', '18');axios.request({url: "http://httpbin.org/post",method: "post",data: post_data
}).then(res => {console.log(res.data);
});
  1. 在浏览器中可以至今使用原生的 FormData 对象
let post_data = new FormData();
post_data.append('name', 'xiaoming');
post_data.append('age', '18');axios.request({url: "http://httpbin.org/post",method: "post",data: post_data
}).then(res => {console.log(res.data);
});

2.4 上传文件

2.4.1 利用FormData对象

  1. 在nodejs中直接将二进制字节流加入到 FormData 对象中。
const axios = require("axios");
const FormData = require('form-data');
const fs = require('fs');let post_data = new FormData();
post_data.append('file', fs.createReadStream('test.png'));axios.request({url: "http://httpbin.org/post",method: "post",data: post_data,
}).then(res => {console.log(res.data);
});
  1. 在浏览器中需要先获取 input 组件选择的文件,再将其添加到 FormData 对象中。

index.html

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><link rel="icon" type="image/svg+xml" href="favicon.svg" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Vite App</title><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head><body><div id="app"></div><input type="file" id="file_input"><button id="sub" onclick="submit()">提交</button><script type="module" src="/main.js"></script>
</body></html>

main.js


// 寻找button
let button = document.querySelector('#sub');
let file = document.querySelector('#file_input');function submit() {let post_data = new FormData();console.log(file.files[0]);post_data.append('file', file.files[0]);axios.request({url: "http://httpbin.org/post",method: "post",data: post_data}).then(res => {console.log(res.data);});
}button.onclick = submit;

2.4.2 直接上传二进制文件

  1. 在nodejs中直接将二进制字节流作为请求体提交。(不要忘记在请求头中设置文件类型)
const axios = require("axios");
const fs = require('fs');axios.request({url: "http://httpbin.org/post",method: "post",data: fs.createReadStream('test.jpg'),headers: { 'content-type': 'image/jpeg' }, // 设置文件类型为图像
}).then(res => {console.log(res.data);
});
  1. 在浏览器中需要先获取 input 组件选择的文件,将其转换为字节流后作为请求体提交。
    index.html (不要忘记在请求头中设置文件类型)
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><link rel="icon" type="image/svg+xml" href="favicon.svg" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Vite App</title><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head><body><div id="app"></div><input type="file" id="file_input"><button id="sub" onclick="submit()">提交</button><script type="module" src="/main.js"></script>
</body></html>

main.js


// 寻找button
let button = document.querySelector('#sub');
let file = document.querySelector('#file_input');function submit() {console.log("Hello");axios.request({url: "http://httpbin.org/post",method: "post",data: file.files[0],headers: { 'content-type': 'image/jpeg' }, // 设置文件类型为图像}).then(res => {console.log(res.data);});
}button.onclick = submit;

3. 参数详解

3.1 函数别名

3.1.1 主要方法

  • axios(config)

  • axios(url[, config])

3.1.2 别名方法

为了方便起见,axios 为所有支持的请求方法提供了别名。

  • 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]])

3.1.3 使用示例

// 下面3种写法是一样的axios({method: 'get',url: 'http://httpbin.org/get',params: {name: "CloudSir"}
});axios.request('http://httpbin.org/get', {method: 'get',params: {name: "CloudSir"}
});axios.get('http://httpbin.org/get', {params: {name: "CloudSir"}
});

3.2 request config 参数

{// `url` 是用于请求的服务器 URLurl: '/get',// `method` 是创建请求时使用的方法method: 'get', // 默认值// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL// 真实请求的 URL 地址是 baseURL+url,可以不设置baseURL,将完整地址放在url钟baseURL: 'http://httpbin.org',// `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 验证auth: {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 // 默认值}

3.3 response 参数

axios.get('http://httpbin.org/get').then(function (res) {// res 参数的结构如下
});
// res的结构{// `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: {}
}

3.4 error 参数

axios.get('http://httpbin.org/get').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);
});

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

axios.get('http://httpbin.org').catch(function (error) {console.log(error.toJSON());
});

3.5 Axios对象

编写大型项目时,会使用多个axios,每个都需要配置统一的 base_url、header 等,我们可以利用 axios.create 创建一个公共的 Axios对象 :

const my_request = axios.create({baseURL: 'http://httpbin.org',headers: {'X-Custom-Header': 'foobar'}
});

当需要使用 Axios 发生请求时:

my_request.get(url: "/get")
.then(res => {console.log(res.data);
});

4. 拦截器

4.1 拦截器简介

拦截器 是在请求发出之前或收到后端的响应后对数据进行统一的处理:

  • 请求拦截器:在请求发送前进行必要操作处理,例如添加统一cookie、请求体加验证、设置请求头等,相当于是对每个接口里相同操作的一个封装;

  • 响应拦截器:响应拦截器也是如此功能,只是在请求得到响应之后,对响应体的一些处理,通常是数据统一处理等,也常来判断登录失效等。

4.2 请求拦截器

// 添加请求拦截器
axios.interceptors.request.use(function (config) {// 在发送请求之前做些什么return config;}, function (error) {// 对请求错误做些什么return Promise.reject(error);
});

4.3 响应拦截器

// 添加响应拦截器
axios.interceptors.response.use(function (response) {// 2xx 范围内的状态码都会触发该函数。// 对响应数据做点什么return response;}, function (error) {// 超出 2xx 范围的状态码都会触发该函数。// 对响应错误做点什么return Promise.reject(error);
});

4.4 移除拦截器

如果你需要移除拦截器,可以将拦截器赋给一个变量,并在需要移除时调用axios.interceptors.XXX.eject函数:(XXX是requestreponse)

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

5. 参考资料

  • Axios官方文档:https://www.axios-http.cn/docs/intro
  • Httpbin官网:http://httpbin.org
  • NodeJS环境下使用axios上传文件_vXZH的CSDN博客:https://blog.csdn.net/u013379553/article/details/104871118
  • vue使用axios上传文件(FormData)的方法 - web开发 - 亿速云: https://www.yisu.com/zixun/166698.html
  • 什么是axios拦截器?有哪些作用和使用场景_超人不会飞啊的博客: https://blog.csdn.net/weixin_48585264/article/details/119116018

【前端】Axios完全使用指南相关推荐

  1. 写给前端的算法进阶指南,我是如何两个月零基础刷200题 等推荐

    大家好,我是若川. 话不多说,这一次花了几小时精心为大家挑选了20余篇好文,供大家阅读学习.本文阅读技巧,先粗看标题,感兴趣可以都关注一波,一起共同进步. 前端从进阶到入院 作者ssh就职于字节跳动基 ...

  2. 写给初中级前端的高级进阶指南等

    大家好,我是若川. 话不多说,这一次花了几小时精心为大家挑选了20余篇好文,供大家阅读学习.本文阅读技巧,先粗看标题,感兴趣可以都关注一波,绝对不亏. 程序员成长指北 考拉妹子,一个有趣的且乐于分享的 ...

  3. 前端初学者开发学习视频_初学者学习前端开发的实用指南

    前端初学者开发学习视频 by Nikita Rudenko 通过尼基塔·鲁登科(Nikita Rudenko) 初学者学习前端开发的实用指南 (A practical guide to learnin ...

  4. 《前端跨界开发指南》重磅来袭!

    谨以此书献给相信"努力有用"的你 by 大史不说话 < 前端跨界开发指南:JavaScript工具库原理解析与实战> 先做个自我介绍 我是大史不说话,是一名前端工程师, ...

  5. 前端axios下载excel文件(二进制)的处理方法

    前端axios下载excel文件(二进制)的处理方法 后端生成excel后,前端 click 事件进行下载 ,脱坑记录,亲测有效. lz 使用的是 axios 发起请求 , 首先,介绍一下思路,准备通 ...

  6. 【干货】写给初中级前端的高级进阶指南

    以下文章来源于掘金开发者社区,作者晨曦时梦见兮 我曾经一度很迷茫,在学了Vue.React的实战开发和应用以后,好像遇到了一些瓶颈,不知道该怎样继续深入下去.相信这也是很多一两年经验的前端工程师所遇到 ...

  7. 写给初中级前端的高级进阶指南(万字长文,建议收藏)

    前言 由于公众号文章不允许外链,需要跳转文中链接的同学可以在脚注里找到各个的资源链接,也可以通过点击阅读原文更加方便的跳转链接. 我曾经一度很迷茫,在学了 Vue.React 的实战开发和应用以后,好 ...

  8. 写给初中级前端的高级进阶指南(万字路线)

    前言 我曾经一度很迷茫,在学了 Vue.React 的实战开发和应用以后,好像遇到了一些瓶颈,不知道该怎样继续深入下去.相信这也是很多一两年经验的前端工程师所遇到共同问题,这篇文章,笔者结合自己的一些 ...

  9. Web前端开发面试考点指南

    Web 前端面试指南与高频考题解析指南 第一章 面试准备:简历编写和面试前准备 一般来说,跳槽找工作要经历投递简历.准备面试.面试和谈 offer 四个阶段.其中面试题目会因你的等级和职位而异,从入门 ...

  10. 写给前端的 K8S 上手指南

    K8S 是什么 在回答这个问题之前,让我们一起先了解下 web 应用部署方式的演化过程. 宿主机模式 在我刚接触软件开发的时候,人们部署应用的方式通常是这样的: 首先需要一台服务器,然后在服务器上安装 ...

最新文章

  1. Android Fragment 你应该知道的一切
  2. 启动python内核时发生错误_启动内核时出错
  3. WASM 成为 HTML、CSS 与 JS 之后的第 4 门 Web 语言
  4. 浏览器输入网址回车发生的事情?--
  5. 按GB 11643标准对大陆身份证号码分析验证
  6. 基于STM32(F103ZE)的LD3320语音控制系统
  7. 雨后小故事动态邪恶_当您遇到“邪恶”的问题时,使故事变小
  8. C++程序设计之客户消费积分管理
  9. 数据标准化——scikit-learn
  10. No1.初来乍到,请多指教
  11. Highcharts3D环形图
  12. css3变形 transform中复合写法的注意问题总结
  13. 寒武纪MLU270 平台 CNStream 学习记录
  14. ECMAScript6知识点概要
  15. Win10中找不到gpedit.msc
  16. 【MANO管理模式利弊分析】
  17. OGNL中#、%和$的用法
  18. des算法s盒java实现_DES算法详解
  19. 中国高分系列卫星介绍
  20. 机房一体化监测解决方案

热门文章

  1. Pr 入门教程:如何更改素材属性?
  2. 电脑安装android2.0,应用多开 这才是最适用电脑的安卓—凤凰系统2.0
  3. 单片机延时C语言程序
  4. Android bluetooth介绍(三): 蓝牙扫描(scan)设备分析
  5. 只知道wxid怎么添加好友
  6. 苹果内购 订单验证 21002 坑
  7. 提升 Docker Desktop For macOS 磁盘使用率
  8. 合肥盛荣乒乓球俱乐部学习感悟
  9. 如何在不清空原有配置的情况下修改路由器密码??????
  10. 计算机无法接入工作网络,局域网中电脑无法连接网络怎么处理