你是对的。 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 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
EDIT: 你的问题不清楚。你第一次谈论cookies,但现在你谈论的是httpOnly
饼干。请更具体地提出您的问题。
是无法设置的httpOnly
如果是跨域,React.js 中的 cookies。 React 只负责网站的“视图”。httpOnly
cookie 只能在服务器端设置。客户端 JavaScript 无法读取或设置该特定 cookie,但可以发送它。除非你的 Netlify 中有可以执行服务器端操作的东西,否则我认为这是不可能的。
最好的选择是实际上只使用相同的域。