每當我使用 api 并發送帖子時,我都會收到此錯誤,Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
![錯誤 [ERR_HTTP_HEADERS_SENT]:發送到客戶端后無法設定標頭?](https://img.uj5u.com/2022/05/19/e182ed27abe34d639d9d8b79225c0026.png)
這是代碼!
//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;
我不知道為什么會出現這個錯誤,我該怎么辦?
uj5u.com熱心網友回復:
看看這是否有效:
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;
添加了回傳,因此一旦res.json()完成,它確保下一個不會運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/477727.html
上一篇:MongoDB-如何使用$graphLookup然后$group和$sort之后
下一篇:如何搜索mongodb
