【问题标题】:Why are cookies not being sent?为什么不发送 cookie?
【发布时间】:2021-02-11 23:43:30
【问题描述】:

我是一名新秀 MERN 堆栈开发人员。在这个项目中,我使用 ReactJS 库作为前端和 Express 作为后端框架。

我正在尝试在登录后将 Jsonwebtoken 存储在 cookie 中,但似乎 cookie 不存在。

useEffect(() => {
    Axios.get('https://orign-project-backend.herokuapp.com/user/verify', {withCredentials: true})
    .then((res) => {
        setCurrentUser(res.user)
    })
    .catch(err => {
        console.log(err)
    })
},[])

这是我在主路由上使用的 useEffect 钩子,用于防止用户每次刷新页面时状态消失。它向后端服务器发送一个 GET 请求,然后后端服务器应该验证 jwt,该 jwt 存储在 cookie 中并发送回解码后的 jwt。

  app.get("/user/verify",function(req,res){
    (jwt.verify(req.cookies.token,key.secretOrKey,(err,decodedToken) =>{
      if (err) res.status(404).json(req.cookies)
      else {res.json(decodedToken)};
    }));
  })
  app.post("/user/login",function(req,res){
  let loggedUser = new User({
    user: req.body.user,
    password: req.body.password
  })
  let validateLogin = inputValidator(loggedUser,false);
  if (!validateLogin.isValid) res.status(404).json(validateLogin.error);
  else{
  User.findOne({user: loggedUser.user},(err,userFound) => {
      if (err) res.status(404).json({inputError: "Some error occured!"});
      if (!userFound) res.status(404).json({inputNotFound:"Invalid Username or Password"});
      else {
        bcrypt.compare(loggedUser.password,userFound.password)
        .then((isMatch) => {
          if (isMatch){
            console.log(userFound._id)
            const payload = {
              user: userFound.user,
              id: userFound._id
            };
            jwt.sign(payload,key.secretOrKey,{expiresIn: 300000},(err,token) => {
              if (err) res.status(404).json({cannotSign:"error when signing jwt"})
              else  {
                res.cookie('token', token, { httpOnly: true,maxAge: 360000 });
                res.json({token})
              }
            })
          }
          else res.status(404).json({inputNotFound:"Invalid Username or Password"})
        })
      }
    })}
  })

这是登录API和用户验证API的代码(后端部署在heroku上,前端运行在本地主机上

const corsOptions = {
origin: "http://localhost:3000",
credentials: true}
app.use(cors(corsOptions))

这是我的 cors 配置。

问题是每次我登录后尝试刷新页面时,服务器总是发送一个错误说令牌无效。然后我发现根本没有发送 cookie,可能是因为登录后我确实在每个 POST 和 GET 请求中都包含了{withCredentials: true}。 (如果发生错误,尝试将 cookie 作为 json 发送回来,结果它是空的)

编辑:登录 API 和用户验证 API 工作正常,cookie 发送正常(在 Postman 中测试)

如果这个问题不简洁或不清楚,我真的很抱歉,这是我第二次提问。

【问题讨论】:

    标签: node.js reactjs express heroku cookies


    【解决方案1】:

    出于安全原因,在从不同端口设置 cookie 时,浏览器的工作方式与 Postman(和其他工具)不同。即使您没有 CORS 错误,浏览器也不会接受 cookie 请求,因为您可能必须满足某些安全协议。

    我发现您的 cookie 代码没有 Secure 参数。例如,Chrome 需要将 cookie 设置为 secure = true 和 sameSite = "none",当它们被服务器部署在与 FE 不同的端口上时。它们还需要在 HTTPS 连接(不是 HTTP)上运行。

    如果您在 Chrome 中遇到此错误,请确保所有这三个设置都正确。

    【讨论】:

      猜你喜欢
      • 2022-08-05
      • 2012-02-10
      • 2019-05-19
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多