【问题标题】:ExpressJS Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clientExpressJS 错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
【发布时间】:2021-11-30 02:23:11
【问题描述】:

第一次命中请求成功,但第二次失败。我的代码有问题吗?谢谢

我的错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我的代码 =

router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    !user && res.status(401).json("Wrong credentials!");

    const hashedPassword = CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    );
    const OriginalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

    OriginalPassword !== req.body.password &&
      res.status(401).json("Wrong credentials!");

    const accessToken = jwt.sign(
      {
        id: user._id,
        isAdmin: user.isAdmin,
      },
      process.env.JWT_SEC,
      { expiresIn: "3d" }
    );

    const { password, ...others } = user._doc;

    res.status(200).json({...others, accessToken});
  } catch (err) {
    res.status(500).json(err);
  }

})

【问题讨论】:

    标签: node.js express postman


    【解决方案1】:

    首先将值传播到您的对象中,然后更新值

    const { ...others, password } = user._doc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 2018-09-19
      • 2021-01-25
      • 2020-09-22
      • 2023-01-19
      • 2021-02-26
      • 2021-08-20
      • 2019-09-28
      相关资源
      最近更新 更多