Here is the code. I am trying to post a login request for authentication to mongodb server using postman. The error is: error in vscode
My code is:
router.post("/login", async (req,res) => {
try{
const user = await User.findOne({username:req.body.username})
!user && res.status(401).json("Wrong username");
const hashed = CryptoJS.AES.decrypt(user.password, process.env.USER_PASS)
const password = hashed.toString(CryptoJS.enc.Utf8);
password !==req.body.password && res.status(401).json("Wrong password");
res.status(200).json(user);
}catch(err){
return res.status(500).json(err)
}
})
module.exports = router
CodePudding user response:
Put your case in an if statement like this
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username })
if(!user) {
return res.status(401).json("Wrong username");
}
const hashed = CryptoJS.AES.decrypt(user.password, process.env.USER_PASS)
const password = hashed.toString(CryptoJS.enc.Utf8);
if (password !== req.body.password) {
return res.status(401).json("Wrong password");
}
return res.status(200).json(user);
} catch (err) {
return res.status(500).json(err);
}
})
module.exports = router
CodePudding user response:
When you do the password check you send a 401 response, but the code flow continues and then you try to send the 200 response although you have already sent a response.
Make sure you only send one response, for example (but there are many ways do it):
return password !== req.body.password
? res.status(401).json("Wrong password")
: res.status(200).json(user);