错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置 headers?

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

每当我使用 api 并发送 post、Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

时都会收到此错误

这是代码!

//LOGIN
router.post("/login", async (req, res) => {
    try {
      const user = await User.findOne({ username: req.body.username });
      !user && res.status(400).json("Wrong credentials!");
  
      const validated = await bcrypt.compare(req.body.password, user.password);
      !validated && res.status(400).json("Wrong credentials!");
  
      const { password, ...others } = user._doc;
      res.status(200).json(others);
    } catch (err) {
      res.status(500).json(err);
    }
  });



module.exports = router;

我不知道为什么会出现这个错误,我该怎么办?

看看这是否有效:

router.post("/login", async (req, res) => {
    try {
      const user = await User.findOne({ username: req.body.username });
      if(!user) return res.status(400).json("Wrong credentials!");
  
      const validated = await bcrypt.compare(req.body.password, user.password);
      if(!validated) return res.status(400).json("Wrong credentials!");
  
      const { password, ...others } = user._doc;
      return res.status(200).json(others);
    } catch (err) {
      return res.status(500).json(err);
    }
  });



module.exports = router;

添加了 returns,这样一旦 res.json() 完成,它确保下一个不会 运行。

  • 关键字 return 阻止了代码的 execution。这意味着它之后的任何代码行都不会被执行。
router.post("/login", async (req, res) => {
    try {
      const user = await User.findOne({ username: req.body.username });
      if(!user){
       return res.status(400).json("Wrong credentials!");
      }
  
      const validated = await bcrypt.compare(req.body.password, user.password);
      if(!validated){
        return res.status(400).json("Wrong credentials!");
      }
  
      const { password, ...others } = user._doc;
      return res.status(200).json(others);
    } catch (err) {
      return res.status(500).json(err);
    }
  });