无法从 MERN 应用程序的后端在浏览器中 receive/set cookies,后端托管在 heroku 上,前端托管在 netlify 上

Not able to receive/set cookies in browser from backend in MERN app with backend hosted on heroku and frontend on netlify

我有一个 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中设置httpOnlycookies是不可能的,如果是跨域的话。 React 只负责网站的'view'。 httpOnly cookie 只能在服务器端设置。客户端 JavaScript 无法读取或设置该特定 cookie,但可以发送它。除非你的 Netlify 中有可以进行服务器端操作的东西,否则我认为这是不可能的。

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