【问题标题】:Cookie not added into request headerCookie 未添加到请求标头中
【发布时间】:2020-03-12 22:27:59
【问题描述】:

想再问一个 CORS cookie 问题,我花了很长时间解决这个问题。 情况如下。

我在 nodejs(http://localhost:5000) 中有一个后端 api,以及一个 React 前端应用程序(http://localhost:3000)。 在后端,Cors 设置是这样的。

private initializeCors(){
    this.app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "http://localhost:3000");
      res.header("Access-Control-Allow-Headers", "Content-Type, Accept");
      res.header("Access-Control-Allow-Credentials", "true");
      next();
    });
  }

使用用户名/密码登录时,我在 Fetch Api 中设置了{ credentials: "include" }。 Set-Cookie 已作为响应设置,我可以看到它保存在浏览器中。 Cookie 的格式为“Authorize=TOKEN;HttpOnly;Max-Age=3600;” Cookie in browser

然后当路由到另一个 url 时,它无法从后端检索数据,出现 401 异常。 这是序列调用的代码。

const credentialsInclude : "include" | "omit" | "same-origin" | undefined = "include";
function getAllPayments() {
    const requestOptions = {
        method: 'GET',
        credentials: credentialsInclude
    };
    return fetch(apiUrls.GET_ALL_PAYMENTS, requestOptions).then(handleResponse);    
}

我可以看到 cookie 没有添加到标题中。 No cookie in header

我已按照here 的最佳答案进行操作,但无法正常工作。

有什么建议吗?谢谢。

【问题讨论】:

    标签: cookies cross-domain


    【解决方案1】:

    我刚刚想通了。该问题不是由 CORS 设置引起的。它是由 Cookie 本身引起的。 对于我的情况,我需要在响应标头中将 Path=/; 添加到 Set-Cookie 中。这样响应中的 cookie 就可以在成功登录后添加到顺序请求中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 2012-05-02
      • 2016-03-24
      • 2012-12-01
      • 2017-02-15
      • 1970-01-01
      相关资源
      最近更新 更多