Axios 教程展示了如何使用 Axios 客户端库在 JavaScript 中生成请求。查看 JavaScript 获取教程,了解在 JavaScript 中创建请求的替代方法。
公理
Axios 是浏览器和 Node.js 的基于承诺的 HTTP 客户端。Axios 可以轻松地将异步 HTTP 请求发送到 REST 端点并执行 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 响应对象包括:
- data – 从服务器返回的负载
- status – 从服务器返回的HTTP代码
- statusText – 从服务器返回的HTTP状态信息
- headers – 服务器发送的headers
- config – 原始请求配置
- request – 请求对象
带有回调的 Axios GET 请求
在第一个示例中,我们创建了一个简单的 GET 请求。我们使用回调。
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>
带有异步/等待的 Axios GET 请求
以下示例创建相同的请求。这次我们使用async/await语法。
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
get、post 或delete 方法是基本 axios API 的便捷方法:axios(config) 和 axios(url, config)。
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();
该示例创建了对webcode.me 的 GET 请求。
const config = {
method: 'get',
url: 'http://webcode.me'
}
我们在配置对象中指定请求的详细信息。
Axios HEAD 请求
HEAD 请求是没有消息正文的 GET 请求。在 Axios 中,使用 head 创建 HEADrequest。
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 请求是否已成功完成。响应分为五类:
- 信息响应 (100-199)
- 成功响应 (200-299)
- 重定向 (300-399)
- 客户端错误 (400-499)
- 服务器错误 (500-599)
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 自定义标头
在下面的示例中,我们发送一个自定义标头。
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。
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();
我们使用URLSearchParams 模块的url 将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 生成请求。
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 方法创建的。
Axios 在作为第二个参数传递给post 函数时自动将JavaScript 对象序列化为JSON;我们不需要将 POST 正文序列化为 JSON。
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,数据在请求正文中发送;键和值被编码在由“&”分隔的键值元组中,键和值之间有一个“=”。
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 下载图像。
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');
我们包括axios 和fs 模块。
var config = {
responseType: 'stream'
};
我们在配置对象中指定响应类型。
let resp = await axios.get(url, config);
我们得到图像。
resp.data.pipe(fs.createWriteStream('image.jpg'));
在fs 模块的帮助下,我们将图像保存到磁盘。
Axios 多请求
我们可以使用 Axios 一次创建多个请求。
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.org',
'https://fsharp.org',
'https://symfony.com',
'https://www.perl.org',
'https://www.php.net',
'https://www.python.org',
'https://code.visualstudio.com',
'https://github.com'
];
doRequests(urls);
该示例生成对给定 URL 列表的异步请求。它打印网站的 URL、服务器名称和状态代码。
const fetchUrl = (url) => axios.get(url);
axios.get 发出异步请求并返回承诺。
let responses = await Promise.all(promises);
我们用Promise.All收集所有承诺。该方法在所有给定的 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.org -> AmazonS3: 200 https://fsharp.org -> GitHub.com: 200 https://symfony.com -> cloudflare: 200 https://www.perl.org -> Combust/Plack (Perl): 200 https://www.php.net -> myracloud: 200 https://www.python.org -> nginx: 200 https://code.visualstudio.com -> Microsoft-IIS/10.0: 200 https://github.com -> GitHub.com: 200
将 Axios 与 JSON 服务器一起使用
JSON Server 是一个很棒的工具,它使我们能够轻松地创建假的 REST API。
$ npm i -g json-server
我们安装json-server。
{
"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 的用户。
发布用户
我们发布了一个新用户。
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('http://localhost:3000/users/', params);
console.log(res.data);
}
makePostRequest();
该示例发布了一个新用户。
let res = await axios.post('http://localhost:3000/users/', params);
post 参数作为第二个参数传递给post方法。
获取用户
我们从测试服务器获取用户。
const axios = require('axios');
async function doGetRequest() {
let res = await axios.get('http://localhost: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 删除资源。
const axios = require('axios');
async function doDeleteRequest() {
let res = await axios.delete('http://localhost:3000/users/2/');
console.log(res.status);
}
doDeleteRequest();
该示例删除 ID 为 2 的用户。
Axios 代理
代理是请求资源的客户端和提供该资源的服务器之间的中介。
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();
该示例通过代理创建网络请求。
在本文中,我们使用了 JavaScript Axios 模块。
列出所有 JavaScript 教程。
