Axios是一個基於promise的HTTP庫,可以用在瀏覽器和node.js中。
- 安裝
- npm install axios --save
- cnpm install axios --save
- 使用CDN <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- GET請求
axios.get('/getUserInfo?id=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可選地,上面的請求可以這樣做
axios.get('/getUserIngo', {
params: {
id: 1
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- POST請求
axios.post('/user', {
firstName: 'newName',
lastName: 'lastName'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- 執行多個併發請求
function getUserAccount() {
return axios.get('/getUserInfo/1');
}
function getUserPermissions() {
return axios.get('/getUserInfo/1/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 兩個請求現在都執行完成
}));