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

7gs2gvoe  于 9个月前  发布在  Postman
关注(0)|答案(2)|浏览(120)

我正在做一个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-parsercors

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

我试过在没有任何选择的情况下使用cors。还是不行。
当我将请求cookie记录到控制台时,

[Object: null prototype] {}

但是使用postman,我得到了控制台中显示的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)
  }
}
f8rj6qna

f8rj6qna1#

httpOnly cookies由服务器设置,只能由服务器访问,浏览器无法访问。当你发出请求时,尝试在axios中添加withCredentials: true(或者在fetch中添加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

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

rkttyhzu

rkttyhzu2#

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

相关问题