当我使用 Postman 时 Cookie 有效,但在浏览器中不显示

pap*_*i3d 5 cookies node.js npm express pug

我正在开发 Nodejs 项目和哈巴狗模板。当我登录邮递员时,会发送 Cookie,但是当我使用 Chrome 或任何其他浏览器时,它不会显示 Cookie

const signToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  })
}

const createSendToken = (user, statusCode, req, res) => {
  const token = signToken(user._id)

  res.cookie('jwt', token, {
    expires: new Date(
      Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
  })


  res.status(statusCode).json({
    status: 'success',
    token,
    data: {
      user,
    },
  })
}
Run Code Online (Sandbox Code Playgroud)

我也在使用npm 的cookie-parsercors

app.use(
  cors({
    credentials: true,
  })
)
Run Code Online (Sandbox Code Playgroud)

我尝试过使用 cors,没有任何选项。还是不行。

当我将 req.cookies 记录到控制台时,我得到

[Object: null prototype] {}
Run Code Online (Sandbox Code Playgroud)

但是使用邮递员,我得到了控制台中显示的 jwt 令牌。

这是我的登录路线。我如何包含凭据

export const login = async (email, password) => {
  try {
    const res = await axios({
      method: 'POST',
      url: 'http://127.0.0.1:3000/api/v1/users/login',
      data: { email, password },
    })

    if (res.data.status === 'success') {
      showAlert('success', 'Logged in successfully!')
      window.setTimeout(() => {
        location.assign('/')
      }, 1500)
    }
    console.log(res)
  } catch (err) {
    showAlert('error', err.response.data.message)
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 1

httpOnly cookie 由服务器设置,浏览器无法访问,只能由服务器访问。当提出请求时,尝试添加withCredentials: trueaxios (或credentials: 'include'用于 fetch):

axios.post('/your-route', {your-body}, {withCredentials: true});
-- or --
fetch('/your-route', {credentials: 'include'}) 
//may need cross-origin or same-origin if CORS Origin is set
Run Code Online (Sandbox Code Playgroud)

查看有关使用 http cookie 的 mozilla 文档以获取更多参考 https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies