【前端】Axios完全使用指南

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", // 请求url
    method: "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", // 请求url
    method: "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

扫描二维码关注公众号,回复: 14659035 查看本文章
<!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` 是用于请求的服务器 URL
  url: '/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, Buffer
  data: {
    
    
    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 requests
  responseEncoding: '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/cancellation
  cancelToken: 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. 参考资料

猜你喜欢

转载自blog.csdn.net/qq_34802028/article/details/124063573