ZetCode

Axios 教程

最后修改于 2023 年 10 月 18 日

Axios 教程展示了如何使用 Axios 客户端库在 JavaScript 中生成请求。查看 JavaScript fetch 教程,了解在 JavaScript 中创建请求的另一种方法。

Axios

Axios 是一个基于 Promise 的 HTTP 客户端,适用于浏览器和 Node.js。Axios 使向 REST 端点发送异步 HTTP 请求和执行 CRUD 操作变得容易。它可以在纯 JavaScript 中使用,也可以与 Vue 或 React 等库一起使用。

在本文中,我们在 Node.js 应用程序中使用 Axios。

设置 Axios

首先,我们安装 Axios。

$ node -v
v18.2.0

我们使用 Node.js 版本 18.2.0。

$ npm init -y

我们启动一个新的 Node.js 应用程序。

$ npm i axios

我们使用 npm i axios 命令安装 Axios。

Axios 发送请求

在 axios 中有多种创建请求的方法。

axios(config) 
axios(url[, config])

这些是用于在 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]])

这些是方法别名,为了方便而创建。

Axios 响应对象

当我们向服务器发送请求时,它会返回一个响应。Axios 响应对象由以下部分组成:

使用回调的 Axios GET 请求

在第一个示例中,我们创建一个简单的 GET 请求。我们使用回调。

main.js
const axios = require('axios');

axios.get('http://webcode.me').then(resp => {

    console.log(resp.data);
});

我们生成一个简单的 GET 请求并显示输出。

const axios = require('axios');

包含了 Axios 库。

axios.get('http://webcode.me').then(resp => {

    console.log(resp.data);
});

使用 get,我们发送一个 GET 请求。我们输出响应中的数据。数据是 HTML 代码。

$ node main.js
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My html page</title>
</head>
<body>

    <p>
        Today is a beautiful day. We go swimming and fishing.
    </p>

    <p>
          Hello there. How are you?
    </p>

</body>
</html>

使用 async/await 的 Axios GET 请求

以下示例创建相同的请求。这次我们使用 async/await 语法。

main.js
const axios = require('axios');

async function doGetRequest() {

  let res = await axios.get('http://webcode.me');

  let data = res.data;
  console.log(data);
}

doGetRequest();

该示例使用 async/await 语法创建一个简单的 GET 请求。

Axios 基本 API

getpostdelete 方法是基本 axios API 的便捷方法:axios(config)axios(url, config)

main.js
const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'get',
        url: 'http://webcode.me'
    }

    let res = await axios(config)

    console.log(res.status);
}

makeRequest();

该示例创建一个 GET 请求到 webcode.me

const config = {
    method: 'get',
    url: 'http://webcode.me'
}

我们在配置对象中指定请求的详细信息。

Axios HEAD 请求

HEAD 请求是不带消息体的 GET 请求。在 Axios 中,HEAD 请求是用 head 创建的。

main.js
const axios = require('axios');

async function doHeadRequest() {

  let res = await axios.head('http://webcode.me');

  console.log(`Status: ${res.status}`)
  console.log(`Server: ${res.headers.server}`)
  console.log(`Date: ${res.headers.date}`)
}

doHeadRequest();

该示例显示了使用 HEAD 请求生成的响应的状态、服务器名称和响应日期。

$ node main.js
Status: 200
Server: nginx/1.6.2
Date: Sun, 19 Jun 2022 12:49:06 GMT

Axios 状态码

HTTP 响应状态代码指示特定的 HTTP 请求是否已成功完成。响应分为五个类

main.js
const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'head',
        url: 'http://webcode.me'
    }

    let res = await axios(config)

    console.log(res.status);
}

makeRequest();

我们从响应的 status 属性获取状态码。

$ node main.js
200

Axios 自定义标头

在下面的示例中,我们发送一个自定义标头。

main.js
const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'get',
        url: 'http://webcode.me',
        headers: { 'User-Agent': 'Axios - console app' }
    }

    let res = await axios(config)

    console.log(res.request._header);
}

makeRequest();

该示例发送一个自定义标头。

const config = {
    method: 'get',
    url: 'http://webcode.me',
    headers: { 'User-Agent': 'Axios- console app' }
}

自定义数据被添加到配置对象的 headers 属性中。

console.log(res.request._header);

我们验证发送的数据。

$ node main.js
GET / HTTP/1.1
Accept: application/json, text/plain, */*
User-Agent: Console app
Host: webcode.me
Connection: close

Axios GET 请求查询参数

在下面的示例中,我们向 URL 附加一些查询参数。

main.js
const axios = require('axios');
const url = require('url');

async function doGetRequest() {

    let payload = { name: 'John Doe', occupation: 'gardener' };

    const params = new url.URLSearchParams(payload);

    let res = await axios.get(`http://httpbin.org/get?${params}`);

    let data = res.data;
    console.log(data);
}

doGetRequest();

我们使用 url 模块的 URLSearchParams 将 JSON 对象转换为合适的 URL 查询形式。

$ node main.js
{
  args: { name: 'John Doe', occupation: 'gardener' },
  headers: {
    Accept: 'application/json, text/plain, */*',
    Host: 'httpbin.org',
    'User-Agent': 'axios/0.21.1',
    'X-Amzn-Trace-Id': 'Root=1-6023ba22-48b1ff807ea9d934457abbcd'
  },
  ...
  url: 'http://httpbin.org/get?name=John+Doe&occupation=gardener'
}

获取 Github 信息

许多在线服务都包含公共 API。在下面的示例中,我们生成一个对 Github API 的请求。

main.js
const axios = require('axios');

async function getNumberOfFollowers() {

  let res = await axios.get('https://api.github.com/users/janbodnar');

  let nOfFollowers = res.data.followers;
  let location = res.data.location;

  console.log(`# of followers: ${nOfFollowers}`)
  console.log(`Location: ${location}`)
}

getNumberOfFollowers();

在示例中,我们获取用户的关注者数量和位置。

$ node main.js 
# of followers: 324
Location: Bratislava

Axios POST JSON 请求

POST 请求是用 post 方法创建的。

当 JavaScript 对象作为第二个参数传递给 post 函数时,Axios 会自动将其序列化为 JSON;我们不需要将 POST 主体序列化为 JSON。

main.js
const axios = require('axios');

async function doPostRequest() {

    let payload = { name: 'John Doe', occupation: 'gardener' };

    let res = await axios.post('http://httpbin.org/post', payload);

    let data = res.data;
    console.log(data);
}

doPostRequest();

该示例创建一个 POST 请求到在线测试服务。有效负载是 post 函数的第二个参数。

$ node main.js
{
  args: {},
  data: '{"name":"John Doe","occupation":"gardener"}',
  files: {},
  form: {},
  headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Length': '43',
      'Content-Type': 'application/json',
      Host: 'httpbin.org',
      'User-Agent': 'axios/0.27.2',
      'X-Amzn-Trace-Id': 'Root=1-62af1bac-13b255536674047051875828'
  },
  json: { name: 'John Doe', occupation: 'gardener' },
  ...
  url: 'http://httpbin.org/post'
}

Axios POST FORM 请求

在下面的示例中,我们生成一个包含表单数据的 POST 请求。

$ npm i form-data

我们安装 form-data 模块。

使用 application/x-www-form-urlencoded 时,数据在请求的正文中发送; 键和值以键值对的形式编码,用 '&' 分隔,键和值之间用 '=' 分隔。

main.js
const axios = require('axios');
const FormData = require('form-data');

async function doPostRequest() {

    const form_data = new FormData();
    form_data.append('name', 'John Doe');
    form_data.append('occupation', 'gardener');

    let res = await axios.post('http://httpbin.org/post', form_data, 
        { headers: form_data.getHeaders() });

    let data = res.data;
    console.log(data);
}

doPostRequest();

为了生成适当格式的表单数据,我们使用 FormData 对象。

$ node main.js
{
  args: {},
  data: '',
  files: {},
  form: { name: 'John Doe', occupation: 'gardener' },
  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Length': '284',
    'Content-Type': 'multipart/form-data; boundary=--------------------------487292688876562281304473',
    Host: 'httpbin.org',
    'User-Agent': 'axios/0.27.2',
    'X-Amzn-Trace-Id': 'Root=1-62af1c03-32fb934410edf8130cabe019'
  },
  json: null,
  ...
  url: 'http://httpbin.org/post'
}

Axios 下载图片

以下示例展示了如何使用 Axios 下载图片。

main.js
const axios = require('axios');
const fs = require('fs');

var config = {
    responseType: 'stream'
};

let url = 'https://images.dog.ceo/breeds/setter-english/n02100735_4870.jpg';

async function getImage() {

    let resp = await axios.get(url, config);
    resp.data.pipe(fs.createWriteStream('image.jpg'));
}

getImage();

该示例从一个在线服务检索图片,该服务保存着狗的图片。

const axios = require('axios');
const fs = require('fs');

我们包含 axiosfs 模块。

var config = {
    responseType: 'stream'
};

我们在配置对象中指定响应类型。

let resp = await axios.get(url, config);

我们获取图片。

resp.data.pipe(fs.createWriteStream('image.jpg'));

借助 fs 模块,我们将图片保存到磁盘。

Axios 多个请求

我们可以使用 Axios 一次创建多个请求。

main.js
const axios = require('axios');

async function doRequests(urls) {

    const fetchUrl = (url) => axios.get(url);
    const promises = urls.map(fetchUrl);

    let responses = await Promise.all(promises);

    responses.forEach(resp => {
        let msg = `${resp.config.url} -> ${resp.headers.server}: ${resp.status}`;
        console.log(msg);
    });
}

let urls = [
    'http://webcode.me',
    'https://example.com',
    'http://httpbin.org',
    'https://clojure.net.cn',
    'https://fsharp.org',
    'https://symfony.com.cn',
    'https://perl.net.cn',
    'https://php.ac.cn',
    'https://pythonlang.cn',
    'https://vscode.js.cn',
    'https://github.com'
];

doRequests(urls);

该示例生成对给定 URL 列表的异步请求。它打印网站的 URL、服务器名称和状态码。

const fetchUrl = (url) => axios.get(url);

axios.get 发出一个异步请求并返回一个 Promise。

let responses = await Promise.all(promises);

我们使用 Promise.All 收集所有 Promise。该方法在所有给定的 Promise 都已完成或被拒绝后解析。

$ node multiple_requests.js
http://webcode.me -> nginx/1.6.2: 200
https://example.com -> ECS (dcb/7F83): 200
http://httpbin.org -> gunicorn/19.9.0: 200
https://clojure.net.cn -> AmazonS3: 200
https://fsharp.org -> GitHub.com: 200
https://symfony.com.cn -> cloudflare: 200
https://perl.net.cn -> Combust/Plack (Perl): 200
https://php.ac.cn -> myracloud: 200
https://pythonlang.cn -> nginx: 200
https://vscode.js.cn -> Microsoft-IIS/10.0: 200
https://github.com -> GitHub.com: 200

将 Axios 与 JSON Server 一起使用

JSON Server 是一个很棒的工具,它允许我们轻松创建假的 REST API。

$ npm i -g json-server

我们安装 json-server

users.json
{
  "users": [
    {
      "id": 1,
      "first_name": "Robert",
      "last_name": "Schwartz",
      "email": "rob23@gmail.com"
    },
    {
      "id": 2,
      "first_name": "Lucy",
      "last_name": "Ballmer",
      "email": "lucyb56@gmail.com"
    },
    {
      "id": 3,
      "first_name": "Anna",
      "last_name": "Smith",
      "email": "annasmith23@gmail.com"
    },
    {
      "id": 4,
      "first_name": "Robert",
      "last_name": "Brown",
      "email": "bobbrown432@yahoo.com"
    },
    {
      "id": 5,
      "first_name": "Roger",
      "last_name": "Bacon",
      "email": "rogerbacon12@yahoo.com"
    }
  ]
}

这是我们的测试数据。

启动 JSON 服务器

JSON 服务器是使用 json-server 启动的,我们已经全局安装了它。

$ json-server --watch users.json    

--watch 选项用于指定服务器的数据。

$ curl localhost:3000/users/2/
{
  "id": 2,
  "first_name": "Lucy",
  "last_name": "Ballmer",
  "email": "lucyb56@gmail.com"
}

使用 curl 命令,我们获取 ID 为 2 的用户。

发布一个用户

我们发布一个新用户。

main.js
const axios = require('axios');

async function makePostRequest() {

    params = {
        id: 6,
        first_name: 'Fred',
        last_name: 'Blair',
        email: 'freddyb34@gmail.com'
      }

    let res = await axios.post('https://:3000/users/', params);

    console.log(res.data);
}

makePostRequest();

该示例发布一个新用户。

let res = await axios.post('https://:3000/users/', params);

发布参数作为第二个参数传递给 post 方法。

获取用户

我们从测试服务器获取用户。

main.js
const axios = require('axios');

async function doGetRequest() {

  let res = await axios.get('https://:3000/users/');

  let data = res.data;
  console.log(data);
}

doGetRequest();

此程序从我们的测试服务器检索所有用户。

$ node main.js
[ { id: 1,
    first_name: 'Robert',
    last_name: 'Schwartz',
    email: 'rob23@gmail.com' },
  { id: 2,
    first_name: 'Lucy',
    last_name: 'Ballmer',
    email: 'lucyb56@gmail.com' },
  { id: 3,
    first_name: 'Anna',
    last_name: 'Smith',
    email: 'annasmith23@gmail.com' },
  { id: 4,
    first_name: 'Robert',
    last_name: 'Brown',
    email: 'bobbrown432@yahoo.com' },
  { id: 5,
    first_name: 'Roger',
    last_name: 'Bacon',
    email: 'rogerbacon12@yahoo.com' },
  { id: 6,
    first_name: 'Fred',
    last_name: 'Blair',
    email: 'freddyb34@gmail.com' } ]

删除一个用户

资源是用 delete 删除的。

main.js
const axios = require('axios');

async function doDeleteRequest() {

    let res = await axios.delete('https://:3000/users/2/');

    console.log(res.status);
}

doDeleteRequest();

该示例删除 ID 为 2 的用户。

Axios 代理

代理是客户端请求资源和提供该资源的服务器之间的中间人。

main.js
const axios = require('axios');

async function doGetRequest() {

    let host = 'proxy';
    let port = 8080;

    const res = await axios.get('http://webcode.me', {
        proxy: {
            host: host,
            port: port 
        }
    });

    console.log(res.data);
}

doGetRequest();

该示例通过代理创建一个 Web 请求。

来源

Axios 文档

在本文中,我们使用了 JavaScript Axios 模块。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

查看 所有 JavaScript 教程。