当我使用Postman时Cookie可以工作,但在浏览器中不显示

问题描述 投票:0回答:3

我正在开发 Nodejs 项目和 pug 模板。当我登录邮递员时,会发送 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,
    },
  })
}

我也在使用 npm 的

cookie-parser
cors

app.use(
  cors({
    credentials: true,
  })
)

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

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

[Object: null prototype] {}

但是使用邮递员,我在控制台中显示了 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)
  }
}
node.js express npm cookies pug
3个回答
1
投票

httpOnly cookie 由服务器设置,浏览器无法访问,只能由服务器访问。当提出请求时,尝试在 axios 中添加

withCredentials: true
(或
credentials: 'include'
用于获取):

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

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


0
投票

我不得不寻找它,一整天,我发现使用 http://localhost:3000 而不是 http://127.0.0.1:3000 就是我所需要的解决方案,试试这个...... .


0
投票

请帮助我,发生了同样的问题

© www.soinside.com 2019 - 2024. All rights reserved.