且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

axios拦截器响应未定义

更新时间:2023-11-21 16:09:34

由于浏览器在执行预检时收到了401未经授权的响应$ c> OPTION $ c,因此您未收到您对Axios所做请求的回复$ c>请求,导致您尝试执行的请求出现网络错误

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.

这与 CORS 的工作方式以及后端如何处理 OPTION 请求。要了解后端服务器应如何处理预检请求,了解引入预检请求的动机是什么非常重要。

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.

后端服务器不应检查 OPTION 请求的身份验证,它应该验证是否正在向端点发出请求接受跨域请求并返回成功代码。

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.

这样,如果不再对用户进行身份验证,Axios拦截器将收到401错误代码。

That way, the Axios interceptor will receive the 401 error code if the user is no longer authenticated.

无耻的自我推销,我发布了一个简单的Axios插件,名为 axios-middleware 有助于在更大的应用程序中抽象使用Axios拦截器。它提供了一个示例通过尝试进行身份验证来自动处理未经身份验证的请求的中间件再次重新发送请求之前。

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.