首页 > 解决方案 > 无法在浏览器应用程序选项卡中使用 NodeJs 设置 Cookie,即使它响应

问题描述

我处于一个奇怪的情况,cookie 没有在浏览器中设置,作为响应它在浏览器中显示

在此处输入图像描述

来自网络选项卡的响应屏幕截图 在此处输入图像描述

在域上运行的 React 应用程序 - https://2367cc15b.eu.ngrok.io

在域上运行的节点 Js - https://e17b14c2835b.ngrok.io

设置cookie的代码

res.cookie('holofyKey', holofyKey, { httpOnly: true, domain: '.ngrok.io', expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) });

app.use(cookieParser());在我的中间件中使用。

有什么我想念的吗?

PS - 我尝试从选项中删除 httpOnly 和域名仍然没有运气

标签: node.jsexpresscookies

解决方案


在尝试了所有可能的解决方案 2 天后,这终于对我有用

这就是您需要调用要从中设置 cookie 的 api 的方式。

const postHelper = async (url, body) => {
  return await fetch(url, {
    method: "POST",
    headers: {
      Accept: "applicaiton/json",
      "Content-Type": "application/json",
    },
    body: body && JSON.stringify(body),
    withCredentials: true, // should be there
    credentials: 'include' // should be there
  });
};

添加后你会得到 CORS 错误所以请在你的服务器中添加这行代码

app.use(cors({ origin: true, credentials: true }));

最后

res.cookie('cookieKey', cookieKey, { expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)), secure: true  });

PS - 此解决方案适用于跨域和同域的情况,但在跨域的情况下,大多数浏览器在用户同意之前不允许您设置 cookie。


推荐阅读