NodeJS cookie在本地主机上页面重新加载后消失

fivyi3re  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(180)

当您进入网站时,设置了cookie,一切正常,但当您重新加载页面时,设置的cookie将被删除
登录响应(back):

  1. export const sendAccessTokenAndRefreshToken = (response:ServerResponse, accesstoken:string, refreshtoken:string) => {
  2. response.writeHead(200, {
  3. 'Content-Type': 'text/json; application/json',
  4. "Access-Control-Allow-Credentials": "true",
  5. "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
  6. "Access-Control-Allow-Origin": "http://localhost:3000",
  7. "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
  8. 'Set-Cookie': [`refreshtoken=${refreshtoken}; Secure; HttpOnly; SameSite=None; Path=/; Max-Age=99999999;`]
  9. });
  10. response.end(JSON.stringify({accesstoken}));
  11. }

响应选项(cors):

  1. response.writeHead(200, {
  2. 'Content-Type': 'text/json; application/json',
  3. "Access-Control-Allow-Credentials": "true",
  4. "Access-Control-Allow-Origin": "http://localhost:3000",
  5. "Access-Control-Expose-Headers": "Authorization",
  6. "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
  7. });
  8. response.end(JSON.stringify({message: 'Cors Work!'}));

登录完成后:
enter image description here
站点重新加载后:
enter image description here
在这张图片中,你可以看到当发送一个post请求时,cookie会显示,但是在重新启动后它会消失。
enter image description here
front login.js:

  1. const body = {
  2. login: login_input.value,
  3. password: password_input.value
  4. }
  5. fetch('http://127.0.0.1:3000/login', {
  6. method: 'POST',
  7. mode: 'cors',
  8. headers: {
  9. 'Content-Type': 'application/json'
  10. },
  11. credentials: 'include',
  12. body: JSON.stringify(body)
  13. })
  14. .then((response) => response.json())
  15. .then((json) => {
  16. localStorage.setItem('token', json.accesstoken);

如何解决这一问题?我尝试使用cors浏览器扩展,但即使这样也没有帮助
如何解决这个问题,而不诉诸于无关的框架?

hmtdttj4

hmtdttj41#

我怀疑是在下面的代码中使用了'和'引号:
“Access-Control-Allow-Headers”:“EST-Control-Allow-Headers,Origin,X-Requested-With,Content-Type,Accept,Authorization”,'Set-Cookie':[ refreshtoken=${refreshtoken}; Secure; HttpOnly; SameSite=None; Path=/; Max-Age=99999999; ]
删除"“,也删除[],你不应该有它。
例如:

  1. "Set-Cookie": "refreshtoken=${refreshtoken}; Secure; HttpOnly; SameSite=None; Path=/; Max-Age=99999999;"

那么将刷新令牌存储在cookie中是否是一个好主意是另一个问题,但这是另一个讨论。
为了补充这个答案,我写了一篇博客文章,更详细地介绍了这个主题:Debugging cookie problems

相关问题