Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Exit after res.send() in Express.js

Exit after res.send() in Express.js

Problem

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?

Problem courtesy of: Rob Wilkerson

Solution

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]));

[My apologies for not posting this in a comment, not enough reputation yet]

Solution courtesy of: Floby

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Exit after res.send() in Express.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×