1、简介javascript
看看官网的简介:html
“Promise based HTTP client for the browser and node.js” java
译:基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用。node
2、特色:ios
一、在浏览器中发送 XMLHttpRequests 请求;
二、在 node.js 中发送 http请求;
三、支持 Promise API;
四、拦截请求和响应;
五、转换请求和响应数据;
六、自动转换 JSON 数据;
七、客户端支持保护安全免受 XSRF 攻击;es6
3、安装(官网)npm
4、应用axios
一、发送一个get请求promise
axios.get('/welfare', {
params: {
giftPackId: 1
}
})
.then(function(res) {
console.log(res);
})
.catch(function (res) {
console.log(res);
});浏览器
二、发送一个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);
});
|
三、发送多个并发请求
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
}));
|
四、除此以外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]])
|
五、兼容性处理
项目中发现,在安卓4.3及如下的手机不支持axios的使用,主要就是没法使用promise。加上如下polyfill就能够了。
项目中安装es6-promise
1
|
cnpm install es6-promise --save-dev
|
在axios.min.js开头加上
1
|
require(
'es6-promise'
).polyfill();
|
ok!