【问题标题】:Cookie works when I use Postman, but does not show in browser使用 Postman 时 Cookie 有效,但在浏览器中不显示
【发布时间】:2021-11-27 22:11:16
【问题描述】:

我正在开发一个 Nodejs 项目和 pug 模板。当我在 postman 上登录时,会发送 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


    【解决方案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

    【讨论】:

    • 我刚刚修改了我最初的问题以包含我的 axios 帖子,我该如何使用凭证来完成它
    • const res = await axios({method: 'POST', url: URL, data: {DATA}, withCredentials: true})
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2019-10-22
    • 2016-07-29
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多