node.js - 无法在浏览器应用程序选项卡中使用 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 和域名仍然没有运气
解决方案
在尝试了所有可能的解决方案 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。
推荐阅读
- sql - 比较在不同时间更新的同一唯一项目的同一列中的值
- flutter - FutureBuilder 显示 AlertDialog - 将焦点放在 TextField 时,所有者小部件会重建
- c - 在 C 中打印这种特定三角形图案的最佳方式/方法是什么?
- c# - 是否可以在 Xamarin 项目中使用已经创建的 Sqlite 数据库?
- python - 使用 python-pep8 出错
- r - 每次运行代码时,是否可以使用特定功能来分配不同的名称?
- snakemake - snakemake “rule all” 正在重新运行不必要的规则
- android - 在可见性可见后如何对recyclerview进行ui测试
- python - Selenium 信用卡模块元素不可交互
- windows - 视窗。文件权限在从一个 NTFS 磁盘复制到另一个 NTFS 磁盘期间更改