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

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

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

export const sendAccessTokenAndRefreshToken = (response:ServerResponse, accesstoken:string, refreshtoken:string) => {

    response.writeHead(200, {
        'Content-Type': 'text/json; application/json',
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
        "Access-Control-Allow-Origin": "http://localhost:3000",
        "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
        'Set-Cookie':  [`refreshtoken=${refreshtoken}; Secure; HttpOnly; SameSite=None; Path=/; Max-Age=99999999;`]
       
    });

    response.end(JSON.stringify({accesstoken}));

}

响应选项(cors):

response.writeHead(200, {
    'Content-Type': 'text/json; application/json',
    "Access-Control-Allow-Credentials": "true",
    "Access-Control-Allow-Origin": "http://localhost:3000",
    "Access-Control-Expose-Headers": "Authorization",
    "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
});

response.end(JSON.stringify({message: 'Cors Work!'}));

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

const body = {

    login: login_input.value,
    password: password_input.value

}

fetch('http://127.0.0.1:3000/login', {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json'
    },
    credentials: 'include',
    body: JSON.stringify(body)
})
.then((response) => response.json())
.then((json) => {
    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; ]
删除"“,也删除[],你不应该有它。
例如:

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

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

相关问题