NodeJS 未在Vercel中设置但在本地工作的Cookie

cu6pst1q  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(89)

部署到Vercel后,无法在以下函数中设置Cookie:

const logIn = (req, res) => {
  const { email, password, cookieAge } = req.body;
  const throwError = (res) => res.status(500).send({ message: "The credentials are incorrect. Please try again." });
  let userFound;
  User
    .findOne({ email: email })
    .then(user => {
      userFound = user;
      return bcrypt.compare(password, user.password);
    })
    .then(passwordValidation => {
      if (passwordValidation) {
        const token = jwt.sign({ userId: userFound.id }, process.env.JWT_SECRET);
        // console.log("token:", token);
        res.cookie("access-token", token, { maxAge: cookieAge, domain: ".vercel.app" });
        res.json(true);
      } else {
        throwError(res);
      }
    })
    .catch(() => throwError(res));
};

以下是响应头:

那么问题出在哪里呢?

vatpfxk5

vatpfxk51#

我解决了这个问题,因为我有同样的问题。我改变了响应链的顺序。在机体React之前,先设置库克。请参见响应截图中设置的cookie

...
  response.setHeader('Set-Cookie',['type=ninja']).status(200).json({
    body: res
  });

相关问题