Axios 是基于 promise 的http库,可在nodejs服务端或客户端浏览器运行
其中浏览器使用XMLHttpRequests对象进行请求
Github地址
特点
- 支持服务端和客户端
- 基于Promise
- 支持请求和响应拦截
- 支持JSON格式转换
- 支持取消请求
安装
1 | npm install axios |
或者1
bower install axios
或者直接引入1
<script src="//raw.githubusercontent.com/axios/axios/9005a54a8b42be41ca49a31dcfda915d1a91c388/dist/axios.min.js"></script>
使用
get
1 | axios.get('/info') |
如果需要传参数,可以直接加在 url ,也可以用params1
2
3
4
5
6
7
8
9axios.get('/info',{
params: { id: 123, time: 12345}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
post
1 | axios.post('/info',{ |
request
get和post都是简化的请求,同时axios提供类似了jQuery.ajax的api,可以直接配config
上面2个改下如下1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22axios.request({
url: '/info',
method: 'get',
params: { id: 123, time: 12345}
}.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
axios.request({
url: '/info',
method: 'post',
data: {
id: 123,
name: 'Gavin'
}
}.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
delete
这个主要在RESTful规范API会用到1
2
3
4
5
6
7axios.delete('/user/123')
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
put
同delete方法,主要用于修改接口1
2
3
4
5
6
7axios.put('/user/123', jsonObj)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
head
head用法同get,但是只返回header信息,不会有response body
可以节省很多带宽,主要用途
- 测试连接可用性
- 检验页面有没改动
- 藏在header的数据检验
1 | axios.head("/info", { params: {"id": 123}}) |
all
同Promise的all,可以传入请求数组,当请求全部完成时执行回调1
2
3
4
5
6
7
8
9axios.all([
axios.get('//google.com'),
axios.get('//163.com'),
axios.get('//qq.com')
]).then(
res => {
console.log(res)
}
);all
传入数组,回调返回的 response
其实也是数组
spread
这个方法用来展开多个response返回值,我自己没实际用过,谷歌了也没发现具体用途,不知道跟数组是什么优势,有知道的麻烦说一下1
2
3
4
5
6
7
8
9
10
11axios.all([
axios.get('//google.com'),
axios.get('//163.com'),
axios.get('//qq.com')
]).then(
axios.spread((res1,res2,res3) => {
console.log(res1)
console.log(res2)
console.log(res3)
})
);