axios响应拦截器:响应回到then/catch之前,触发的拦截函数,对响应结果统一处理。也就是说,在回到具体逻辑之前的拦截处理。
axios响应拦截器,什么时候触发成功/失败的回调函数?
状态为 2xx 的触发成功回调,其它则触发失败的回调函数。
例如:
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 2xx 范围内的状态码都会触发该函数
return response
}, function (error) {
// 超过2xx 范围的状态码都会触发该函数
// 对响应错误做点什么,例如,统一对401身份验证失败情况做出处理
console.dir(error)
if (error?.response?.status === 401) {
alert('身份验证失败,请重新登录')
localStorage.clear()
location.href = '../login/index.html'
}
return Promise.reject(error)
})