Exit after res.send() in Express.js
If you are using express as your framework, you should call next() instead.
Each handler in express receives 3 parameters (unlinke 2 for basic http) which are req
, res
and next
next
is a function that when called with no arguments will trigger the next handler in the middleware chain.
If next
is called with an arguments, this argument will be interpreter as an error, regardless of the type of that argument.
Its signature is next([error])
. When next is called with an error, then instead of calling the next handler in the middleware chain, it calls the error handler. You should handle the 401 response code in that error handler. See this for more info on error handling in Express
EDIT: As @Baptiste Costa commented, simply calling next()
will not cease the current execution but it will call on the next middleware. It is good practice to use return next()
instead to prevent Node from throwing errors further on (such as the can't set headers after they are sent
- error). This includes the above suggestion of error throwing which is common:
return next(new Error([error]));
Of course express can not magically make your javascript function stop executing from somewhere else.
I don't like the next([error]) solution because I think errors should be only used for circumstances you usually don't expect (like an unreachable database or something). In this case, a simple wrong password would cause an error. It is a common convention to not use exceptions/errors for ordinary control flow.
I therefore recommend to place a return statement after the res.send call to make your function stop executing further.
client.login( username, password, function( auth, client ) {
if( !auth ) {
res.send( 401 );
return;
}
// DO OTHER STUFF REALLY ONLY IF AUTH IS SUCCESSFUL
}