【问题标题】:res.cookie set the token on the localhost but not on serverres.cookie 在本地主机上设置令牌,但不在服务器上
【发布时间】:2021-10-18 09:28:22
【问题描述】:

function setTokenCookie(res, token) {
    console.log(token,"pop")
    // create cookie with refresh token that expires in 7 days
    const cookieOptions = {
        httpOnly: true,
        expires: new Date(Date.now() + 7*24*60*60*1000)
    };
    res.cookie('refreshToken', token, cookieOptions);
}

当尝试在本地主机上设置 cookie 时,它​​工作得很好,但是我在服务器上上传了我的后端,当时它没有设置 cookie

【问题讨论】:

    标签: node.js cookies token backend


    【解决方案1】:

    我的猜测是您的后端域与您的前端不同,因此仍然需要更多选项来确保设置 cookie。

    function setTokenCookie(res, token) {
      console.log(token,"pop")
      // create cookie with refresh token that expires in 7 days
      const cookieOptions = {
          httpOnly: true,
          expires: new Date(Date.now() + 7*24*60*60*1000),
          secure: process.env.NODE_ENV !== 'development',
          sameSite: 'lax',
          path: '/'
      };
      res.cookie('refreshToken', token, cookieOptions);
    }
    

    如果您的后端域与前端域相同,那么您可以将 sameSite 属性设置为“严格”。当您不处于开发模式时,secure 属性也应设置为 true。

    如果你问我的个人喜好,我会使用 cookie 库设置 cookie,如下所示:

     res.setHeader('Set-Cookie', cookie.serialize("refreshToken", token, {
            httpOnly: true,
            secure: process.env.NODE_ENV !== 'development',
            sameSite: 'strict',
            maxAge: 60 * 60 * 24 * 7,
            path: '/'
        }))
    

    此外: 完成上述配置后,在发出 fetch 请求时,不要忘记在 fetch/axios req 选项中将 withCredential 设置为“true”,以确保 set cookie 随请求一起发送。

    【讨论】:

    • 我检查了 req.cookies 它来自前端的空值,但在前端值存在这个问题只发生在服务器上,因为 localhost 它完美地工作我正在使用前端反应
    • 在前端的请求选项中将 withCredential 标志设置为 true,如果未设置为 true,则不会将您的 cookie 与请求一起发送,这就是 req.cookies 为空的原因
    • 兄弟,我检查一下它已经是凭据的代码:添加了包含标志。但还是报错
    猜你喜欢
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    相关资源
    最近更新 更多