今天在做一个关于vue的后端管理系统时,遇到了axios语法糖async和await的用法,以及axios请求拦截器的使用。由于对这两个方面不太熟悉,所以想对axios的使用做一下总结。
什么是axios ?
Axios 是一个基于 promise 的 HTTP 库,它专注于网路数据请求。
axios的使用
axios支持各种数据请求方式,在这里只以get和post为例。
发送get请求:
// 第一种携带数据的方式,使用查询字符串的方式,这也是get请求携带参数的方式
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
// 第二种携带数据的方式
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then回调函数是处理请求发送成功后的响应结果。调用 axios 方法得到的返回值是 Promise 对象。response中的数据不是接口返回的真实数据,response.data才是真实数据
.catch回调函数捕捉请求发送失败的接结果
发送post请求:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios发送请求:
//发送post请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// 发送get请求
axios({
method: 'get',
url: '/user',
params: {
id: 123456
}
})
// 若不写methods默认是get请求
async/await:
在ECMAScript 2017中提供了axios的语法糖,可以简化axios发送请求。async写在函数前,await写在该函数中的axios请求前。
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
执行多个并发请求:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});
全局的 axios 默认值
axios.defaults.baseURL = 'https://api.example.com';
拦截器
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
// 移除拦截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);