gpt4 book ai didi

node.js - 无法从 MERN 应用程序的后端在浏览器中接收/设置 cookie,后端托管在 heroku 上,前端托管在 netlify 上

转载 作者:行者123 更新时间:2023-12-04 07:58:07 25 4
gpt4 key购买 nike

我有一个 MERN 应用程序,其后端托管在 Heroku 上,前端托管在 netlify 上。部署应用程序后,我无法在浏览器中看到 cookie,但它在本地主机上运行良好。我认为这是由于后端和前端端口不同,我缺少什么,请帮忙

最佳答案

你是对的。 Cookie 不跨域兼容。如果是,那将是一个严重的安全问题。解决问题的最简单方法是将 cookie 作为 res 对象发回,然后在前端手动设置 cookie。

以这个为例。我将使用 JavaScript 风格的伪代码来完成这项工作。不要复制粘贴它,因为这很可能不会立即起作用。这是您要在后端执行的操作:

// 1. Authenticate the user.
const userData = await authenticateUser();
const userToken = await verifyUser(userData);

// 2. Return the response object.
return response.status(200).json({
status: 'success',
data: userData,
token: userToken,
});

在前端:

const response = await axios.post(...); // your API call, will return above object.

// set your authentication token here.
// the 'options' object will contain all possible cookie options, example would be 'secure'.
cookies.set('token', response.data.token, options);

// alternatively, set the cookie in the local storage.
localStorage.setItem('token', response.data.token);

您需要在前端相应地设置cookie。

进一步阅读:MDN Docs


编辑:您的问题不清楚。您第一次谈论 cookie,但现在您谈论的是 httpOnly cookie。请在您的问题中更具体。

在React.js中是不可能设置httpOnly cookies的,如果是跨域的话。 React 只负责网站的“ View ”。 httpOnly cookie 只能在服务器端设置。客户端 JavaScript 无法读取或设置该特定 cookie,但可以发送它。除非您的 Netlify 中有可以执行服务器端操作的东西,否则我认为这是不可能的。

您最好的选择是实际上只使用相同的域。

关于node.js - 无法从 MERN 应用程序的后端在浏览器中接收/设置 cookie,后端托管在 heroku 上,前端托管在 netlify 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66595631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com