特征
1.从浏览器中创建XMLHttpRequests。
2.从node.js创建http请求。
3.支持Promise API。
4.拦截请求和响应。
5.转换请求数据和响应数据。
6.取消请求。
7.自动转换JSON数据。
并发请求
methods: {
sendAjax() {
// 请求1 get
// 请求2 post
this.$axios.defaults.baseUrl = 'http://127.0.0.1:8888';
var res1 = this.$axios.get('');
var res2 = this.$axios.post('add', 'a=1');
this.$axios.all([res1, res2]).then(this.$axios.spread((res1, res2) => {
// 请求成功
this.res1 = res1.data;
this.res2 = res2.data;
})).catch(err => {
// 请求失败
console.log(err);
});
}
}
axios 传递相关配置来创建请求
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// 获取远端图片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
请求方法别名(restful接口规范可以用到)
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]])
拦截器
methods: {
sendAjax() {
// 模拟类似cookie机制
// 添加请求拦截器
this.$axios.interceptors.request.use((config) => {
// 在发送请求之前做些什么
let token = localStorage.getItem('token');
if(token) {
config.headers['token'] = token;
}
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
this.$axios.interceptors.response.use((response) => {
// 对响应数据做点什么
if(response.data.token) {
localStorage.setItem('token', response.data.token);
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
}
}