express - Cookie 未与 Fetch 一起存储

标签 express cookies fetch jwt redux

我已经阅读了我能找到的所有其他主题,但没有一个解决方案有效。我正在使用 React + Redux + Express 并尝试按照以下方式将 JWT 存储在 cookie 中:

https://auth0.com/blog/2015/09/28/5-steps-to-add-modern-authentication-to-legacy-apps-using-jwts/

在我的 Redux 操作中,我发送了以下请求:

export function getCookie(token) {
  const config = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + token
    },
    body: JSON.stringify({ token })
  };
  return fetch('http://127.0.0.1:4000/authorize-cookie', config)
   .then((res) => {
     return res.json();
   })
   .then((resJson) => {
     return resJson;
   })
   .catch(err => console.log('Error: ', err));
}

在服务器上,我正在响应...
app.post('/authorize-cookie', authenticate, (req, res) => {
  res.cookie('id_token', req.body.token, {
    maxAge: 360000
  });
  res.status(200).send({ message: 'Cookie set!' });
});

...其中authenticate 是验证 token 的函数。

我的响应头看起来一切正常:
HTTP/1.1 200 OK
Set-Cookie: id_token=xxx.xxx.xxx; Max-Age=360; Path=/; Expires=Tue, 12 Jan 2016 01:24:03 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 25
ETag: W/"19-UA3htFr0PWczMQBN6T4NpA"
Date: Tue, 12 Jan 2016 01:18:03 GMT
Connection: keep-alive

但是当我检查源选项卡时,没有找到 cookie。我读过关于关闭 httpOnly 和安全以及使用 localhost 的问题。我也尝试过每个主要浏览器,但没有运气。

这里发生了什么?

最佳答案

你遇到了一个有趣的案例。问题是 fetch 的行为功能不同于 XMLHttpRequest .在 fetch 中使用 cookie您应该明确提供 credentials选项。

fetch('http://127.0.0.1:4000/authorize-cookie', {
    method: 'POST',
    body: JSON.stringify({token: token}),
    credentials: 'same-origin', // <- this is mandatory to deal with cookies
})

根据 the article on MDN

Credentials: The request credentials you want to use for the request: omit, same-origin, or include. To automatically send cookies for the current domain, this option must be provided.

关于express - Cookie 未与 Fetch 一起存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34734208/

相关文章:

javascript - 所有数组元素均未分配给模型

javascript - cookie 中未设置 token

reactjs - 跨站点 cookie 问题 : how to set cookie from backend to frontend

node.js - 无法从本地主机获取数据

node.js - 通过app.use进行中央错误处理

javascript - 如何从 Node 中的 module.exports 链调用函数

node.js - 如何在保存之前检查该数据是否已存在于数据库中

ASP.NET:身份验证过期时如何获取 FormsAuthenticationTicket 对象

javascript - Const 被视为字符串 React.JS/fetch

javascript - Node 获取响应为 503,其中请求响应为代理后面的 200