Skip to content
Advertisement

Cannot set headers after they are sent to the client (Node.js)

So basically when I try to log a user in and I type the password or username wrong and then I try to log in with correct credentials I get this error.

JavaScript

And this is my code in auth.js

JavaScript

What should I do? Is something wrong with my code?

Advertisement

Answer

!user && res.status(401).json('Wrong User Name');

as a statement is IMHO quite bad style. And as you see, it leads to errors, because your code doesn’t step out of this handler after having sent the headers. It just continues with the next statment and eventually reaches another res.status(...). This will try to set some headers again, which isn’t allowed. And that’s what the error message is telling you.

Use

JavaScript

instead. This will return from handler and not execute the remaining code in your function … Same of course for all other instances where you use this pattern.

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