I have a fairly simple Express.js app with a login component that I’d like to exit early if login fails. I’m seeing indications that the app isn’t doing that and I haven’t found a definitive answer that indicates whether calling res.send() halts any further processing. Here’s my code as it stands now:
client.login( username, password, function( auth, client ) {
if( !auth ) {
res.send( 401 );
}
// DO OTHER STUFF IF AUTH IS SUCCESSFUL
}
If I read the source code correctly, it should end the request (aborting further processing), but I’m new to node, so I’m not quite ready to trust what I think I’m reading. To boil it down, I guess I’m mostly looking for a definitive answer from a more trustworthy source that my own interpretation of unfamiliar source code. If send() doesn’t abort processing, what’s the right way to do that?
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,resandnextnextis a function that when called with no arguments will trigger the next handler in the middleware chain.If
nextis 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 ExpressEDIT: 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 usereturn next()instead to prevent Node from throwing errors further on (such as thecan't set headers after they are sent– error). This includes the above suggestion of error throwing which is common: