一个用于浏览器和node.js的基于Promise的HTTP客户端。
为什么舍弃vue-resources? 因为vue-resources不再更新了, Vue2.0之后官方更推荐axios。而且axios也更强大。
github/axios 浏览器支持
特征
- 在浏览器中发送 XMLHttpRequests 请求
- 在 node.js 中发送 http请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持保护安全免受 CSRF/XSRF 攻击
安装
npm install axios
使用
import axios from 'axios';
get
axios.get(url)
.then(res => {
console.log(res);
}).catch(error => {
console.log(error);
});
error.response 你会用到的
axios.get(url)
.catch(error => {
if(error.response){
// 2XX 状态码之外的处理
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
// 在设置触发错误的请求时发生了错误
console.log('Error',error.message);
}
});
添加头部信息
axios.get(url, {
headers:{
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
console.log(res);
}).catch(error => {
console.log(error);
});
post
axios.post(url, data)
.then(res => {
console.log(res);
}).catch(error => {
console.log(error);
});
more
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