一个用于浏览器和node.js的基于Promise的HTTP客户端。
为什么舍弃vue-resources? 因为vue-resources不再更新了, Vue2.0之后官方更推荐axios。而且axios也更强大。
github/axios
浏览器支持

特征
- 在浏览器中发送 XMLHttpRequests 请求
- 在 node.js 中发送 http请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持保护安全免受 CSRF/XSRF 攻击
安装
使用
1
| import axios from 'axios';
|
get
1 2 3 4 5 6
| axios.get(url) .then(res => { console.log(res); }).catch(error => { console.log(error); });
|
error.response 你会用到的
1 2 3 4 5 6 7 8 9 10 11 12
| axios.get(url) .catch(error => { if(error.response){ console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else { console.log('Error',error.message); } });
|
添加头部信息
1 2 3 4 5 6 7 8 9 10
| axios.get(url, { headers:{ 'Content-Type': 'multipart/form-data' } }) .then(res => { console.log(res); }).catch(error => { console.log(error); });
|
post
1 2 3 4 5 6
| axios.post(url, data) .then(res => { console.log(res); }).catch(error => { console.log(error); });
|
more
1 2 3 4 5 6 7 8
| axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])
|
文档
github文档: https://github.com/axios/axios
看云中文文档:https://www.kancloud.cn/yunye/axios/234845