提问者:小点点

Cookie未从响应传递到下一个请求


我正在尝试构建我的第一个Web应用程序,我正在使用cookie进行身份验证。

基本上,我的React客户机将身份验证凭据发送到REST API,REST API验证它并在凭据有效的情况下生成令牌。

当我在chrome上检查网络activity时,令牌设置在/loginPOST请求的响应报头上,但当我在此之后尝试访问受保护的路由时,我得到一个401,检查请求时发现报头上没有cookie。

我该如何对抗? 起初我以为这是CORS的问题,但我似乎无法解决它。

我是如何处理CORS问题的:

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Set-Cookie");
next();
  });

提前谢谢你。


共1个答案

匿名用户

您对受保护路由的下一个POST请求不包含cookie,因为默认情况下它不发送cookie。

如果你使用Axios。

设置with credentials:true

axios.get(`api_url`, { withCredentials: true })

通过设置{WithCredential:true},您可能会遇到跨源问题。 来解决您需要使用的问题

expressApp.use(cors({ credentials: true, origin: "http://localhost:8080" })); //Your REACT ADDRESS

在此阅读有关With Credentials的更多信息:https://developer.mozilla.org/en-us/docs/web/api/XMLHttpRequest/With Credentials