axios 的使用

1.axios 的简介

Axiosopen in new window 是一个基于 Promise 的 HTTP 客户端,用于 node.js 和浏览器。它是同构的(=它可以运行在浏览器和 nodejs 具有相同的代码库)。

  • 在服务器端,它使用本地的 node.js http 模块
  • 而在客户端(浏览器),它使用 xmlhttprequest。

特性:

  • 从浏览器生成 xmlhttprequest

  • 从 node.js 发出 http 请求

  • 支持 Promise API

  • 拦截请求和响应

  • 转换请求和响应数据

  • 取消请求

  • 超时

  • 支持嵌套项的查询参数序列化

  • 自动请求体序列化为:

    -- JSON (application / JSON)

    -- Multipart / FormData (Multipart /form-data)

    -- URL 编码表单(application/x-www-form-urlencoded)

  • 将 HTML 表单作为 JSON 发布

  • 响应中的自动 JSON 数据处理

  • 为浏览器和 node.js 捕获进度,附带额外信息(速度,剩余时间)

  • 为 node.js 设置带宽限制

  • 兼容符合规范的 FormData 和 Blob(包括 node.js)

  • 客户端支持防止 XSRF

2. 安装

使用 npm:

  npm install axios

使用 yarn:

  yarn add axios

为了直接使用 require 导入预构建的 CommonJS 模块(如果您的模块打包器无法自动解析它们),我们提供了以下预构建模块:

const axios = require("axios/dist/browser/axios.cjs"); // browser
const axios = require("axios/dist/node/axios.cjs"); // node

3.使用 axios

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

3.2 POST 请求

postJson 请求

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

postForm 上传文件: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",
    },
  }
);

postForm 数据编码: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",
    },
  }
);

3.3 通过配置来请求

可以向 axios 传递相关配置来创建请求,用法:

axios(config);
// 发起一个post请求
axios({
  method: "post",
  url: "/user/12345",
  data: {
    firstName: "Fred",
    lastName: "Flintstone",
  },
});
// 在 node.js 用GET请求获取远程图片
axios({
  method: "get",
  url: "http://bit.ly/2mTM3nY",
  responseType: "stream",
}).then(function (response) {
  response.data.pipe(fs.createWriteStream("ada_lovelace.jpg"));
});

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

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

3.4 通过实例请求

实例方法,首先获得实例

axios.create([config]);

获得实例的例子

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

实例方法:

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#getUri([config])

3.5 配置的详细参数

创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 GET 方法。

{
  // `url` 是用于请求的服务器 URL
  url: '/user',

  // `method` 是创建请求时使用的方法
  method: 'get', // 默认值

  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: '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, 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
  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.6 响应结构

一个请求的响应包含以下信息。

{
  // `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);
});

或者

async function (){
  const response = await axios.get("/user/12345");
  console.log(response.data);
  console.log(response.status);
  console.log(response.statusText);
  console.log(response.headers);
  console.log(response.config);
}()

当使用 catch,或者传递一个 rejection callback 作为 then 的第二个参数时,响应可以通过 error 对象被使用,正如在错误处理部分解释的那样。

3.7 默认配置

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

全局 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";

自定义实例默认值

// 创建实例时配置默认值
const instance = axios.create({
  baseURL: "https://api.example.com",
});

// 创建实例后修改默认值
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;

配置的优先级

配置将会按优先级进行合并。它的顺序是:在 lib/defaults.js 中找到的库默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后面的优先级要高于前面的。下面有一个例子。

// 使用库提供的默认配置创建实例
// 此时超时配置的默认值是 `0`
const instance = axios.create();

// 重写库的超时默认值
// 现在,所有使用此实例的请求都将等待2.5秒,然后才会超时
instance.defaults.timeout = 2500;

// 重写此请求的超时时间,因为该请求需要很长时间
instance.get("/longRequest", {
  timeout: 5000,
});

3.8 拦截器

在请求或响应被 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 () {
  /*...*/
});

3.9 错误处理

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

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

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

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

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

3.10 取消请求

使用AbortControlleropen in new window来实现取消请求

AbortController 的使用:

  • 我们先使用 AbortController() 构造函数创建一个控制器实例:controller

  • 当 fetch 请求初始化时,我们将 AbortSignal 作为一个选项传递进入请求的选项对象中{ signal:controller.signal }。 这将 signal 和 controller 与 fetch 请求相关联,

  • 我们通过调用 controller.abort() 去中止它

let controller;
const url = "video.mp4";

document.querySelector(".downloadButton").addEventListener("click", fetchVideo);
document.querySelector(".abortButton").addEventListener("click", cancelVideo);

// 下载视频
function fetchVideo() {
  // 构造函数创建一个控制器实例:controller
  controller = new AbortController();

  // 我们将 AbortSignal(controller.signal)作为一个选项传递进入请求的选项对象中
  fetch(url, { signal: controller.signal })
    .then((response) => {
      console.log("下载完成", response);
    })
    .catch((err) => {
      console.error(`下载错误:${err.message}`);
    });
}

// 取消下载
function cancelVideo() {
  if (controller) {
    // 通过调用 controller.abort() 去中止它
    controller.abort();
    console.log("中止下载");
  }
}

axios 使用 AbortController

const controller = new AbortController();

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

3.11 请求体编码

默认情况下,axios 将 JavaScript 对象序列化为 JSON 。

要以 application/x-www-form-urlencoded 格式发送数据,您可以使用以下选项之一。

浏览器

可以使用 qs 库编码数据:

import qs from "qs";
const data = { bar: 123 };
const options = {
  method: "POST",
  headers: { "content-type": "application/x-www-form-urlencoded" },
  data: qs.stringify(data),
  url,
};
axios(options);

Node.js

在 node.js, 您可以使用 qs 库

const qs = require("qs");

axios.post("http://something.com/", qs.stringify({ foo: "bar" }));

也可以使用 form-data 库,如下所示:

const FormData = require("form-data");

const form = new FormData();
form.append("my_field", "my value");
form.append("my_buffer", new Buffer(10));
form.append("my_file", fs.createReadStream("/foo/bar.jpg"));

axios.post("https://example.com", form, { headers: form.getHeaders() });

使用一个拦截器:

axios.interceptors.request.use((config) => {
  if (config.data instanceof FormData) {
    Object.assign(config.headers, config.data.getHeaders());
  }
  return config;
});

自动序列化

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

在浏览器和 node.js 环境中都适用:

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'
  }

如果您的服务器框架的请求体解析器(例如 express.js 的 body-parser)支持嵌套对象解码,则其接收到的数据将与您提交的数据一样。

以下是一个 express.js 的服务器示例,它将会把接收到的数据作为响应返回:

var app = express();

app.use(bodyParser.urlencoded({ extended: true })); // support url-encoded bodies

app.post("/", function (req, res, next) {
  res.send(JSON.stringify(req.body));
});

server = app.listen(3000);

3.12 Multipart 实体请求

使用 FormData API

浏览器

const form = new FormData();
form.append("my_field", "my value");
form.append("my_buffer", new Blob([1, 2, 3]));
form.append("my_file", fileInput.files[0]);

axios.post("https://example.com", form);

Axios 会将传入数据序列化,因此使用 Axios 提供的 API 可以无需手动处理 FormData 的数据并实现一样的效果:

axios.postForm("https://httpbin.org/post", {
  my_field: "my value",
  my_buffer: new Blob([1, 2, 3]),
  my_file: fileInput.files, // FileList will be unwrapped as sepate fields
});

HTML 表单可以直接作为请求内容来进行传输。

NodeJS

import axios from "axios";

const form = new FormData();
form.append("my_field", "my value");
form.append("my_buffer", new Blob(["some content"]));

axios.post("https://example.com", form);

由于 node.js 当前不支持从文件创建 Blob,因此您可以使用第三方软件包来实现该目的。

import { fileFromPath } from "formdata-node/file-from-path";

form.append("my_field", "my value");
form.append("my_file", await fileFromPath("/foo/bar.jpg"));

axios.post("https://example.com", form);

当 Axios 版本小于 v1.3.0 时您必须引入 form-data 包。

const FormData = require("form-data");

const form = new FormData();
form.append("my_field", "my value");
form.append("my_buffer", new Buffer(10));
form.append("my_file", fs.createReadStream("/foo/bar.jpg"));

axios.post("https://example.com", form);

自动序列化

从 v0.27.0 版本开始,当请求头中的 Content-Type 是 multipart/form-data 时,Axios 支持自动地将普通对象序列化成一个 FormData 对象。

这个示例请求演示了如何将一个数据通过 FormData 格式进行提交(浏览器与 Node.js 环境):

import axios from "axios";

axios
  .post(
    "https://httpbin.org/post",
    {
      user: {
        name: "Dmitriy",
      },
      file: fs.createReadStream("/foo/bar.jpg"),
    },
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  )
  .then(({ data }) => console.log(data));

Axios FormData 序列化器支持一些特殊的结尾,以执行以下操作:

  • {} - 通过 JSON.stringify 序列化数据
  • [] - 将 array-like 的对象使用相同的键值来展开为单独的字段 提示:默认情况下,展开、扩展操作将在数组和 FileList 对象上使用。

FormData 序列化器支持通过 config.formSerializer: object 这个参数来传递一些额外的选项,以支持一些特殊的情况:

  • visitor: Function - 用户定义的处理函数,将递归调用以按照自定义规则将数据对象序列化为 FormData 对象。

  • dots: boolean = false - 使用点符号而不是括号来序列化数组和对象;

  • metaTokens: boolean = true - 在 FormData 键值中添加特殊结尾(例如 user{}: '{"name": "John"}')。后端的 body-parser 可能会使用此元信息自动将值解析为 JSON。

  • indexes: null|false|true = false - 控制如何添加索引到打平的 array-like 对象的展开键值中

    -- null - 不添加中括号(arr: 1,arr: 2,arr: 3)

    -- false(默认值)- 添加空中括号(arr[]: 1,arr[]: 2,arr[]: 3)

    -- true - 添加带有索引的中括号(arr[0]: 1,arr[1]: 2,arr[2]: 3)

    示例对象:

    const obj = {
      x: 1,
      arr: [1, 2, 3],
      arr2: [1, [2], 3],
      users: [
        { name: "Peter", surname: "Griffin" },
        { name: "Thomas", surname: "Anderson" },
      ],
      "obj2{}": [{ x: 1 }],
    };
    

    接下来这些序列化的步骤将会由 Axios 内置的序列化器自动执行:

    const formData = new FormData();
    formData.append("x", "1");
    formData.append("arr[]", "1");
    formData.append("arr[]", "2");
    formData.append("arr[]", "3");
    formData.append("arr2[0]", "1");
    formData.append("arr2[1][0]", "2");
    formData.append("arr2[2]", "3");
    formData.append("users[0][name]", "Peter");
    formData.append("users[0][surname]", "Griffin");
    formData.append("users[1][name]", "Thomas");
    formData.append("users[1][surname]", "Anderson");
    formData.append("obj2{}", '[{"x":1}]');
    
    import axios from "axios";
    
    axios
      .post(
        "https://httpbin.org/post",
        {
          "myObj{}": { x: 1, s: "foo" },
          "files[]": document.querySelector("#fileInput").files,
        },
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      )
      .then(({ data }) => console.log(data));
    

Axios 支持以下别名方法:postForm,putForm,patchForm,这些方法只是对应的 HTTP 方法,其 content-type 头部默认设为 multipart/form-data。

FileList 对象可以被直接传递:

await axios.postForm(
  "https://httpbin.org/post",
  document.querySelector("#fileInput").files
);

所有文件将使用相同的字段名 files[]发送。

Contributors: masecho