Skip to content
Advertisement

Login function : Error [ERR_HTTP_HEADERS_SENT]

enter image description here

I’m trying to login as a user on my website and it’s giving me this error, I can register the user and search for it in the login as many times as I want if the password and username are correct, however when there is an error in the user name or password it happens this in postman and even putting the right password and username it does not show the information and stays like this. Only returning to normal when I restart the server.

enter image description here

I’m a beginner and I’m learning, so I don’t know what’s wrong, thank you in advance for your attention.

Advertisement

Answer

The error generally means that you can not send HTTP headers multiple times.

It occurs when username does not match because in line 24 you send status(401) but then code flow continues, trying to send another status() later.

It occurs when password does not match because in line 32 you send status(401), code flow continues and then in the next line (34) you try to send status(201). The last call might send you to the exception handler (catch ..) in which you also try to send another status(500)

to avoid this, you might try:

if (!user) {
    return res.status(401).json('wrong credentials');
} 

//... get password hash from DB...

if (password !== req.body.password) {
    return res.status(401).json('wrong credentials');
}

return res.status(201).json(user);

Important sidenote:
You should NEVER encrypt/decrypt passwords. Store password hashes instead and only ever compare hashes. Use bcrypt!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement