【问题标题】:Not Able to Set Cookie using NodeJs in Browser Application tab even its coming in response无法在浏览器应用程序选项卡中使用 NodeJs 设置 Cookie,即使它会响应
【发布时间】:2021-07-23 16:16:14
【问题描述】:

我处于一个奇怪的情况,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.js express cookies


    【解决方案1】:

    在尝试了所有可能的解决方案 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-07
      • 2019-08-05
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 2019-04-19
      相关资源
      最近更新 更多