有时候我们在axios拦截器的响应失败函数中需要获取请求失败的返回信息,但是通过参数只能获取到错误信息,无法获取响应信息。解决方法是在请求时,将错误信息和响应信息都放入一个自定义的对象中返回,然后在拦截器的响应失败函数中获取该对象,从中取出需要的信息。例如:
axios.interceptors.response.use(response => {
return response;
}, error => {
return Promise.reject({
data: error.response.data,
status: error.response.status,
statusText: error.response.statusText
});
});
axios.get('/api/user')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error.data); // 打印请求失败的响应信息
});
在上述示例中,我们将请求失败的响应信息都放入了一个对象中,对象包含了响应数据、响应状态码和响应状态信息。在拦截器的响应失败函数中,我们reject了这个对象,这样在后续的catch函数中就可以获取到这个对象了,只需从中取出需要的信息即可。
上一篇:Axios的懒加载请求问题
下一篇:Axios的默认超时时间是多少?