來源: http://www.rzrgm.cn/leaf930814/p/6807318.html
-------------------------------------------------------
一、簡介
“Promise based HTTP client for the browser and node.js”
譯:基于 Promise 的 HTTP 請求客戶端,可同時在瀏覽器和 node.js 中使用。
二、特點:
1、在瀏覽器中發送 XMLHttpRequests 請求;
2、在 node.js 中發送 http請求;
3、支持 Promise API;
4、攔截請求和響應;
5、轉換請求和響應數據;
6、自動轉換 JSON 數據;
7、客戶端支持保護安全免受 XSRF 攻擊;
三、安裝(官網)
四、應用
1、發送一個get請求
axios.get('/welfare', {
params: {
giftPackId: 1
}
})
.then(function(res) {
console.log(res);
})
.catch(function (res) {
console.log(res);
});
2、發送一個post請求
|
1
2
3
4
5
6
7
8
9
|
axios.post('/welfare', { giftPackId: 1 }) .then(function (res) { console.log(res); }) .catch(function (res) { console.log(res); }); |
3、發送多個并發請求
|
1
2
3
4
5
6
7
8
9
10
11
12
|
function getUserAccount() { return axios.get('/welfare');}function getUserPermissions() { return axios.get('/getWelfare');}axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // ok })); |
4、除此之外axios還提供還有如下幾種請求方式:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
axios.request(config)axios.get(url[, config])axios.delete(url[, config])axios.head(url[, config])axios.post(url[, data[, config]])axios.put(url[, data[, config]])axios.patch(url[, data[, config]]) |
5、兼容性處理
項目中發現,在安卓4.3及以下的手機不支持axios的使用,主要就是無法使用promise。加上以下polyfill就可以了。
項目中安裝es6-promise
|
1
|
cnpm install es6-promise --save-dev |
在axios.min.js開頭加上
|
1
|
require('es6-promise').polyfill(); |
ok!

浙公網安備 33010602011771號