原文: http://zetcode.com/javascript/axios/

Axios 教程展示了如何使用 Axios 客户端库在 JavaScript 中生成请求。

Axios

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

在本教程中,我们将在 Node.js 应用中使用 Axios。

安装 Axios

首先,我们安装 Axios。

  1. $ node -v
  2. v11.5.0

我们使用 Node.js 11.5 版。

  1. $ npm init -y

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

  1. $ npm i axios

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

Axios 响应对象

当我们向服务器发送请求时,它返回一个响应。 Axios 响应对象包括:

  • data - 服务器返回的有效负载
  • status - 服务器返回的 HTTP 代码
  • statusText - 服务器返回的 HTTP 状态消息
  • header - 服务器发送的标头
  • config - 原始请求配置
  • request - 请求对象

带回调的 Axios GET 请求

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

simple_get.js

  1. const axios = require('axios');
  2. axios.get('http://webcode.me').then(resp => {
  3. console.log(resp.data);
  4. });

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

  1. const axios = require('axios');

包括 Axios 库。

  1. axios.get('http://webcode.me').then(resp => {
  2. console.log(resp.data);
  3. });

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

  1. $node simple_get.js
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>My html page</title>
  9. </head>
  10. <body>
  11. <p>
  12. Today is a beautiful day. We go swimming and fishing.
  13. </p>
  14. <p>
  15. Hello there. How are you?
  16. </p>
  17. </body>
  18. </html>

这是输出。

带有异步/等待的 Axios GET 请求

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

simple_get.js

  1. const axios = require('axios');
  2. async function makeGetRequest() {
  3. let res = await axios.get('http://webcode.me');
  4. let data = res.data;
  5. console.log(data);
  6. }
  7. makeGetRequest();

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

Axios HEAD 请求

HEAD 请求是没有消息正文的 GET 请求。 在 Axios 中,使用head()创建 HEAD 请求。

head_request.js

  1. const axios = require('axios');
  2. async function makeHeadRequest() {
  3. let res = await axios.head('http://webcode.me');
  4. console.log(`Status: ${res.status}`)
  5. console.log(`Server: ${res.headers.server}`)
  6. console.log(`Date: ${res.headers.date}`)
  7. }
  8. makeHeadRequest();

该示例显示了通过 HEAD 请求生成的响应的状态,服务器名称,响应日期。

  1. $ node head_request.js
  2. Status: 200
  3. Server: nginx/1.6.2
  4. Date: Mon, 04 Feb 2019 15:08:56 GMT

这是输出。

Axios 基本 API

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

basic_api.js

  1. const axios = require('axios');
  2. async function makeRequest() {
  3. const config = {
  4. method: 'get',
  5. url: 'http://webcode.me'
  6. }
  7. let res = await axios(config)
  8. console.log(res.status);
  9. }
  10. makeRequest();

该示例向webcode.me创建 GET 请求。

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

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

Axios 自定义标头

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

custom_header.js

  1. const axios = require('axios');
  2. async function makeRequest() {
  3. const config = {
  4. method: 'get',
  5. url: 'http://webcode.me',
  6. headers: { 'User-Agent': 'Console app' }
  7. }
  8. let res = await axios(config)
  9. console.log(res.request._header);
  10. }
  11. makeRequest();

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

  1. const config = {
  2. method: 'get',
  3. url: 'http://webcode.me',
  4. headers: { 'User-Agent': 'Console app' }
  5. }

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

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

我们验证发送的数据。

  1. $ node custom_header.js
  2. GET / HTTP/1.1
  3. Accept: application/json, text/plain, */*
  4. User-Agent: Console app
  5. Host: webcode.me
  6. Connection: close

这是输出。

获取 Github 信息

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

github.js

  1. const axios = require('axios');
  2. async function getNumberOfFollowers() {
  3. let res = await axios.get('https://api.github.com/users/janbodnar');
  4. let nOfFollowers = res.data.followers;
  5. let location = res.data.location;
  6. console.log(`# of followers: ${nOfFollowers}`)
  7. console.log(`Location: ${location}`)
  8. }
  9. getNumberOfFollowers();

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

  1. $ node github.js
  2. # of followers: 44
  3. Location: Bratislava

这是输出。

Axios POST 请求

使用post()方法创建 POST 请求。

post_request.php

  1. const axios = require('axios');
  2. async function makePostRequest() {
  3. let res = await axios.post('https://jsonplaceholder.typicode.com/posts');
  4. console.log(`Status code: ${res.status}`);
  5. console.log(`Status text: ${res.statusText}`);
  6. console.log(`Request method: ${res.request.method}`);
  7. console.log(`Path: ${res.request.path}`);
  8. console.log(`Date: ${res.headers.date}`);
  9. console.log(`Data: ${res.data}`);
  10. }
  11. makePostRequest();

该示例创建对在线测试服务的 POST 请求。

  1. $ node post_request.js
  2. Status code: 201
  3. Status text: Created
  4. Request method: POST
  5. Path: /posts
  6. Date: Mon, 04 Feb 2019 16:54:36 GMT
  7. Data: [object Object]

这是输出。

Axios 下载图像

以下示例显示了如何使用 Axios 下载图像。

get_image.js

  1. const axios = require('axios');
  2. const fs = require('fs');
  3. var config = {
  4. responseType: 'stream'
  5. };
  6. let url = 'httpsimg.dog.ceo/breeds/setter-english/n02100735_4870.jpg';
  7. async function getImage() {
  8. let resp = await axios.get(url, config);
  9. resp.data.pipe(fs.createWriteStream('image.jpg'));
  10. }
  11. getImage();

该示例从在线服务中检索图像,该服务保留了狗的图像。

  1. const axios = require('axios');
  2. const fs = require('fs');

我们包括axiosfs模块。

  1. var config = {
  2. responseType: 'stream'
  3. };

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

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

我们得到图像。

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

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

Axios 多个请求

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

multiple_requests.js

  1. const axios = require('axios');
  2. async function makeRequests() {
  3. let [u1, u2] = await Promise.all([
  4. axios.get('https://api.github.com/users/janbodnar'),
  5. axios.get('https://api.github.com/users/symfony')
  6. ]);
  7. console.log(`Jan Bodnar: ${u1.data.created_at}`);
  8. console.log(`Symfony: ${u2.data.created_at}`);
  9. }
  10. makeRequests();

要发送多个请求,我们使用Promise.all()方法。

  1. $ node multiple_requests.js
  2. Jan Bodnar: 2016-01-31T12:12:28Z
  3. Symfony: 2009-10-24T04:05:23Z

这是输出。

将 Axios 与 JSON 服务器一起使用

JSONServer 是一个很棒的工具,它使我们能够轻松创建伪造的 REST API。

  1. $ npm i -g json-server

我们安装json-server

users.json

  1. {
  2. "users": [
  3. {
  4. "id": 1,
  5. "first_name": "Robert",
  6. "last_name": "Schwartz",
  7. "email": "rob23@gmail.com"
  8. },
  9. {
  10. "id": 2,
  11. "first_name": "Lucy",
  12. "last_name": "Ballmer",
  13. "email": "lucyb56@gmail.com"
  14. },
  15. {
  16. "id": 3,
  17. "first_name": "Anna",
  18. "last_name": "Smith",
  19. "email": "annasmith23@gmail.com"
  20. },
  21. {
  22. "id": 4,
  23. "first_name": "Robert",
  24. "last_name": "Brown",
  25. "email": "bobbrown432@yahoo.com"
  26. },
  27. {
  28. "id": 5,
  29. "first_name": "Roger",
  30. "last_name": "Bacon",
  31. "email": "rogerbacon12@yahoo.com"
  32. }
  33. ]
  34. }

这是我们的测试数据。

启动 JSON 服务器

JSON 服务器从我们已全局安装的json-server启动。

  1. $ json-server --watch data.json

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

  1. $ curl localhost:3000/users/2/
  2. {
  3. "id": 2,
  4. "first_name": "Lucy",
  5. "last_name": "Ballmer",
  6. "email": "lucyb56@gmail.com"
  7. }

使用 curl 命令,使用户获得 ID 2。

发布用户

我们发布了一个新用户。

post_user.js

  1. const axios = require('axios');
  2. async function makePostRequest() {
  3. params = {
  4. id: 6,
  5. first_name: 'Fred',
  6. last_name: 'Blair',
  7. email: 'freddyb34@gmail.com'
  8. }
  9. let res = await axios.post('http://localhost:3000/users/', params);
  10. console.log(res.data);
  11. }
  12. makePostRequest();

该示例发布了一个新用户。

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

post参数作为第二个参数传递给post()方法。

获取用户

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

get_users.js

  1. const axios = require('axios');
  2. async function makeGetRequest() {
  3. let res = await axios.get('http://localhost:3000/users/');
  4. let data = res.data;
  5. console.log(data);
  6. }
  7. makeGetRequest();

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

  1. $ node get_users.js
  2. [ { id: 1,
  3. first_name: 'Robert',
  4. last_name: 'Schwartz',
  5. email: 'rob23@gmail.com' },
  6. { id: 2,
  7. first_name: 'Lucy',
  8. last_name: 'Ballmer',
  9. email: 'lucyb56@gmail.com' },
  10. { id: 3,
  11. first_name: 'Anna',
  12. last_name: 'Smith',
  13. email: 'annasmith23@gmail.com' },
  14. { id: 4,
  15. first_name: 'Robert',
  16. last_name: 'Brown',
  17. email: 'bobbrown432@yahoo.com' },
  18. { id: 5,
  19. first_name: 'Roger',
  20. last_name: 'Bacon',
  21. email: 'rogerbacon12@yahoo.com' },
  22. { id: 6,
  23. first_name: 'Fred',
  24. last_name: 'Blair',
  25. email: 'freddyb34@gmail.com' } ]

这是输出。

删除用户

使用delete()删除资源。

delete_user.js

  1. const axios = require('axios');
  2. async function makePostRequest() {
  3. let res = await axios.delete('http://localhost:3000/users/2/');
  4. console.log(res.status);
  5. }
  6. makePostRequest();

该示例删除具有 ID 2 的用户。

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

您可能也对以下相关教程感兴趣: JSON 服务器教程笑话教程Moment.js 教程从 JavaScript 中的 URL 读取 JSONJavaScript 贪食蛇教程JQuery 教程Node Sass 教程Lodash 教程