Kingsley
Kingsley

Reputation: 71

How do I end this error: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I am learning node.js and express js. I am following a tutorial but mine is generating this error.

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

Though the code works as wanted but I get this error on the console.log. The code is for user authentication for username and password.

Here is the exact code generating this error: This error only happens when I tried to test wrong password or username.

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

    const passValidate = await bcrypt.compare(req.body.password, user.password)
    !passValidate && res.status(400).json("Wrong credentials");

    const {password, ...others} = user._doc;
    res.status(200).json(others)
} catch(err) {
    res.status(500).json(err);
   
}

});

Upvotes: 0

Views: 64

Answers (1)

depperm
depperm

Reputation: 10746

You set res.status(...) three times in your try. Reducing this down to one time will get rid of this error.

router.post("/login", async (req, res) =>{
    try {
        const user = await User.findOne({username: req.body.username})
        let passValidate
        if(user) {
            passValidate = await bcrypt.compare(req.body.password, user.password)
        }

        if(!user || !passValidate) {
            res.status(400).json("Wrong credentials");
        } else {
            const {password, ...others} = user._doc;
            res.status(200).json(others)
        }
    } catch(err) {
        res.status(500).json(err);
    }
});

Upvotes: 1

Related Questions