axios 拦截器响应未定义 [英] axios interceptors response undefined
问题描述
我的用户收到 401 后,我正尝试将其注销.我正在使用 axios 从 api 返回数据
我环顾四周,发现相同的 axios.interceptors.response
axios.interceptors.response.use(响应 =>回复,错误 =>{const {status} = error.response;如果(状态=== 401){store.dispatch('snackBar',snackbarObj)}返回 Promise.reject(error);})
看来我的 error.response 未定义.我不确定出了什么问题?有任何想法吗?
由于浏览器在执行时收到 401 未经授权的响应,因此您没有从使用 Axios 执行的请求中获得响应预检OPTION
请求,导致您尝试执行的请求出现网络错误.
这与 CORS 的工作原理以及如何工作有关您的后端处理 OPTION
请求.要了解后端服务器应如何处理预检请求,重要的是要了解 引入预检请求背后的动机是什么.>
后端服务器不应该检查 OPTION
请求的身份验证,它应该验证请求是向接受跨域请求的端点发出的,如果是,则返回成功代码.
然后,浏览器将自动处理最初预期的请求.
这样,如果用户不再通过身份验证,Axios 拦截器将收到 401 错误代码.
无耻的自我宣传,我发布了一个简单的 Axios 插件,名为 axios-middleware 有助于在较大的应用程序中抽象 Axios 拦截器的使用.它提供了一个中间件的示例,该中间件自动处理未经身份验证的请求在重新发送请求之前尝试再次进行身份验证.
I'm trying to logout my user once they get a 401. I'm using axios to return data from the api
I was looking around and found the same axios.interceptors.response
axios.interceptors.response.use(
response => response,
error => {
const {status} = error.response;
if (status === 401 ) {
store.dispatch('snackBar', snackbarObj)
}
return Promise.reject(error);
}
)
It appears my error.response is undefined. I'm not sure what is wrong? any ideas?
You're not getting a response from the request you're doing with Axios since the browser received a 401 unauthorized response when doing the preflight OPTION
request, resulting in a Network Error for the request you're trying to do.
This is related to how CORS works and how your backend handles OPTION
requests. To understand how the backend server should handle preflight requests, it's important to understand what is the motivation behind introducing preflight requests.
The backend server should not check for authentication on OPTION
requests, it should validate that the request is being made to an endpoint that accepts cross-domain requests and return a success code if it does.
Then, automatically, the browser will proceed with the initially intended request.
That way, the Axios interceptor will receive the 401 error code if the user is no longer authenticated.
Shameless self-promotion, I've published a simple Axios plugin called axios-middleware which helps abstract the use of Axios interceptors in bigger apps. It offers an example of middleware that automatically handles unauthenticated requests by trying to authenticate again before resending the request.
这篇关于axios 拦截器响应未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!