Axios基于 Promise 的 HTTP 客戶端
Axios,基于 Promise 的 HTTP 客戶端,可以工作于瀏覽器中,也可以在 node.js 中使用。
功能:
-
從瀏覽器中創(chuàng)建 XMLHttpRequest
-
從 node.js 中創(chuàng)建 http 請求
-
支持 Promise API
-
攔截請求和響應(yīng)
-
轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
-
取消請求
-
自動(dòng)轉(zhuǎn)換 JSON 數(shù)據(jù)
-
客戶端支持防止 XSRF 攻擊
示例代碼:
執(zhí)行一個(gè) GET 請求
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執(zhí)行一個(gè) POST 請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執(zhí)行多個(gè)并發(fā)請求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));評論
圖片
表情
