如何在 Node.js 中使用 Axios 發出 HTTP 請求
Axios 是一個流行的基於 Promise 的 HTTP 客戶端,用於在 JavaScript 中發出異步 HTTP 請求。它適用於瀏覽器和 Node.js 應用程序。 Axios 提供了一個 API 來處理瀏覽器中的 XHR 和 Node 的 HTTP 接口。
通過使用 Axios,您可以輕鬆地將 HTTP 請求發送到 REST 端點以交換數據。它在所有現代瀏覽器中都能完美運行,包括 Internet Explorer 8 及更高版本。 Axios 還可以用於高級 JavaScript 框架,如 React、Vue.js、Angular 等。
以下是 Axios 支持的完整功能列表:
- 從瀏覽器發出 XMLHttpRequests
- 從 Node.js 發出 HTTP 請求
- 支持 Promise API
- 攔截請求和響應
- 轉換請求和響應數據
- 取消請求
- JSON 數據的自動轉換
- 為防止 XSRF 提供客戶端支持
在本教程中,您將學習如何將 Axios 添加到您的 Node.js 項目並發送不同的 HTTP 請求。為了演示 Axios 在實際場景中的使用,我們將在所有示例中使用 Reqres REST API。
安裝
有多種選項可用於將 Axios 添加到您的項目中。根據你的包管理器,你可以使用 npm:
$ npm install axios --save
或紗線:
$ yarn add axios
或涼亭:
$ bower install axios
或使用 CDN 直接添加到您的網頁:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Axios 基礎 API
如果您已經使用 jQuery 進行異步請求(著名的 $.get()
和 $.post()
方法),更容易理解 Axios API。只需創建一個新的axios實例,然後將相關數據傳遞給axios
啟動 HTTP 請求的對象:
const axios = require('axios');
// Send a GET request
axios({
method: 'get',
url: 'https://reqres.in/api/users',
data: {
name: 'Jane',
country: 'Canada'
}
});
為方便起見,Axios 還為所有支持的 HTTP 請求方法提供了別名:
axios.get(config)
— 使用此方法發出 GET 請求。axios.post(url[, data[, config]])
— 用於發出 POST 請求。axios.put(url[, data[, config]])
— 發出 PUT 請求的別名。axios.patch(url[, data[, config]])
— 使用此方法發送 PATCH 請求。axios.delete(url[, config])
— 顧名思義,它用於發出 DELETE 請求。axios.options(url[, config])
— 想要獲取 CORS 選項?就用這個方法吧。axios.head(url[, config])
— 使用此別名方法獲取 HTTP 標頭。
GET 請求
下面的 Node.js 示例調用 REST Web 服務以使用 axios.get()
檢索用戶列表 方法,然後打印出來。我們正在使用 async/await 語法,它是 ECMAScript 2017 的一部分:
const axios = require('axios');
const listUsers = async () => {
try {
const res = await axios.get('https://reqres.in/api/users');
console.log(res.data.data);
} catch (err) {
console.error(err);
}
};
listUsers();
如果不想使用 async/await 或者想在舊版瀏覽器中使用 Axios,可以使用 Promise 與 REST API 進行通信:
const axios = require('axios');
axios.get('https://reqres.in/api/users')
.then(res => {
console.log(res.data.data);
})
.catch(err => {
console.log(err);
});
GET 帶參數的請求
GET 請求可能在 URL 中包含查詢參數。使用 Axios,您可以向 URL 添加參數,如下所示:
axios.get('https://www.google.com/search?q=axios')
或使用 params
選項中的屬性:
axios.get('https://www.google.com/search', {
params: {
q: 'axios'
}
})
POST 請求
POST 請求用於創建新資源。 axios提供axios.post()
發出HTTP post請求的方法:
const axios = require('axios');
const createUser = async () => {
try {
const res = await axios.post('https://reqres.in/api/users', {
name: 'Atta',
job: 'Freelance Developer'
});
console.log(res.data);
} catch (err) {
console.error(err);
}
};
createUser();
帶有 application/x-www-form-urlencoded
的 POST 請求
默認情況下,Axios 將請求數據對象轉換為 JSON 字符串。在 application/x-www-form-urlencoded
中發送數據 相反,您可以使用 qs 庫或 querystring 模塊對數據進行編碼。
讓我們使用 qs
庫,因為它對嵌套對像有更好的支持。首先,添加 qs
庫到您的項目:
$ npm install qs --save
現在您可以按如下方式使用它:
const axios = require('axios');
const qs = require('qs');
const createUser = async () => {
try {
// set the url
const url = 'https://reqres.in/api/users';
// request data object
const data = {
name: 'John Doe',
job: 'Blogger'
};
// set the headers
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const res = await axios.post(url, qs.stringify(data), config);
console.log(res.data);
} catch (err) {
console.error(err);
}
};
createUser();
PUT 請求
使用 axios.put()
函數,我們可以像下面這樣更新用戶對象:
const axios = require('axios');
const updateUser = async () => {
try {
const res = await axios.put('https://reqres.in/api/users/2', {
name: 'Atta Shah',
job: 'MEAN Stack Developer'
});
console.log(res.data);
} catch (err) {
console.error(err);
}
};
updateUser();
刪除請求
如果你想通過 Axios 使用 REST API 從服務器中刪除一個對象,使用 axios.delete()
方法:
const axios = require('axios');
const deleteUser = async () => {
try {
const res = await axios.delete('https://reqres.in/api/users/2');
console.log(res.status);
} catch (err) {
console.error(err);
}
};
deleteUser();
HEAD 請求
HEAD HTTP 請求只是一個沒有響應正文的 GET 請求。您可以使用 axios.head()
發送 HEAD 請求的方法:
const axios = require('axios');
const retrieveHeaders = async () => {
try {
const res = await axios.head('https://attacomsian.com');
console.log(`Status: ${res.status}`);
console.log(`Content Type: ${res.headers['content-type']}`);
console.log(`Server: ${res.headers.server}`);
console.log(`Date: ${res.headers.date}`);
} catch (err) {
console.error(err);
}
};
retrieveHeaders();
這是上述示例的輸出。它記錄響應狀態代碼 Content-Type
、服務器名稱和日期標題:
Status: 200
Content Type: text/html;charset=UTF-8
Server: nginx/1.14.0 (Ubuntu)
Date: Fri, 23 Aug 2019 11:53:30 GMT
多個並發請求
使用 Axios 的另一個好處是可以並行執行多個 HTTP 請求。您只需將多個 URL 作為數組傳遞給 axios.all()
方法。當所有請求完成後,您將收到一個包含響應對象的數組,其順序與發送順序相同:
const axios = require('axios');
const loadUsers = async () => {
try {
const [res1, res2] = await axios.all([
axios.get('https://reqres.in/api/users/1'),
axios.get('https://reqres.in/api/users/2')
]);
console.log(res1.data);
console.log(res2.data);
} catch (err) {
console.error(err);
}
};
loadUsers();
或者,您可以使用 axios.spread()
將數組展開成多個參數:
const axios = require('axios');
axios.all([
axios.get('https://reqres.in/api/users/1'),
axios.get('https://reqres.in/api/users/2')
]).then(axios.spread((res1, res2) => {
console.log(res1.data);
console.log(res2.data);
}));
錯誤處理
由於 Axios 是一個基於 Promise 的庫,因此處理錯誤很簡單。我們可以使用 catch()
攔截請求執行過程中拋出的任何錯誤的promise方法:
const axios = require('axios');
const unknown = async () => {
try {
const res = await axios.get('https://example.com/unkown');
console.log(res.data);
} catch (err) {
if (err.response) {
// the request went through and a response was returned
// status code in 3xx / 4xx / 5xx range
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
// request was made but server returned no response
console.log(err.request);
} else {
// something went wrong in setting up the request
console.error('Error:', err.message);
}
}
};
unknown();
請求標頭
要發送自定義請求標頭,請將包含標頭的對像作為最後一個參數傳遞:
const axios = require('axios');
const createUser = async () => {
try {
// request data object
const data = {
name: 'Atta',
job: 'Freelance Developer'
};
// request config that includes `headers`
const config = {
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Axios',
'X-Custom-Source': 'Axios Tutorial',
}
};
const res = await axios.post('https://reqres.in/api/users', data, config);
console.log(res.data);
} catch (err) {
console.error(err);
}
};
createUser();
請求配置
以下是發送請求的可用配置選項。只有 url
是必須的。如果沒有method
提供,請求將默認為 GET:
{
// The URL to the request
url: '/users'
// HTTP method like GET, POST, PUT, DELETE, HEAD
method: 'GET',
// optional base url to prepended to `url`
baseURL: 'https://example.com/api',
// HTTP request headers
headers: {
'Content-Type': 'application/json'
},
// query string parameters
params: {
id: 420
},
// request body data object
data: {
name: 'Atta'
},
// request timeout (in milliseconds)
// default `0` (no timeout)
timeout: 10000,
// should credentials go with CORS request?
// default `false`
withCredentials: false,
// http basic authentication
auth: {
username: 'attacomsian',
password: 'top$secret'
},
// the type of response expected
// options are 'arraybuffer', 'document', 'json', 'text', 'stream'
// in browser: `blob` is also available
// default `json`
responseType: 'json',
// define the max. size of the http response content in bytes
maxContentLength: 2000,
// defines the max. number of redirects to follow
// if set to 0, no redirects will be followed.
// default `5`
maxRedirects: 5,
// there are more otpions omitted from this list
// for the sake of brevity
}
響應對象
當我們向服務器發送 HTTP 請求時,它會返迴響應。 axios
返回的響應對象 ,包含以下信息:
{
data: {}, // response that was provided by the server
status: 200, //the HTTP status code from the server response
statusText: 'OK', //the HTTP status message from the server response
headers: {}, //the headers sent by the server (names are lowercased)
config: {}, //the config that was provided to `axios` for the request
request: {} //the request object that generated this response
}
響應數據會自動轉換為 JSON 對象。所以不需要解析。
總結
Axios 是一個基於 Promise 的 HTTP 客戶端庫,用於瀏覽器和 Node.js。它可以與 React 或 Vue.js 等更高級的前端框架以及您的 Node.js 後端應用程序一起使用。
- Axios 為所有 HTTP 動詞提供 HTTP 請求方法,例如
axios.get()
,axios.post()
,axios.put()
等 - Axios 支持 async/await 和 Promise。
- Axios 自動將服務器響應轉換為 JSON 對象。所以不需要使用
JSON.parse()
. - axios提供
axios.all()
同時發送多個請求的功能。
有關更多配置選項,請查看 GitHub 上的 Axios 文檔。如果您想在瀏覽器中使用 Axios,請查看如何在 vanilla JavaScript 中使用 Axios 指南。