Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中
特點
- 支持瀏覽器和node.js
- 支持promise
- 能攔截請求和響應
- 能轉換請求和響應數據
- 能取消請求
- 自動轉換JSON數據
- 瀏覽器端支持防止CSRF(跨站請求僞造)
安裝和使用
npm 安裝
$ npm install axios
bower 安裝
$ bower install axios
使用 cdn:(引入在線地址免去下載導包)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
執行 GET
請求
// 爲給定 ID 的 user 創建請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可選地,上面的請求可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執行 POST
請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執行多個併發請求
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) {
// 兩個請求現在都執行完成
}));
axios 發起 API
請求
axios({
url: 'https://xxxx',
method: 'get', // 請求方式 get 和 post
params: {
// 模擬參數
id // id:id
}
}).then(res => {
// 分析請求到的數據
})
點擊查看 axios中文說明