0

I have this code structure:

app.post('/signin', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
  if (err) { 
    // return next(err);
    return res.send(401)
  }
  if (!user) { 
    return res.send(401); 
  }
    var token = jwt.sign({ user: user}, secret.secretToken, { expiresInMinutes: 60*5 });
    res.json({ token : token });
})(req, res, next);
});

Code works great if I leave the return next(err); line commented out. So where are the benefits if I would use it in conjunction with res.send(401), it possible at all.

I read this: http://howtonode.org/control-flow-part-ii and begin to grasp what is meant, but am not there yet.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147

1 Answers1

0

I think you're missing an error handler in your application.

The error handler is executed when you pass an Error instance to the next function. For example:

app.use(function myErrorHandler(err, req, res, next) {
    console.log(err);
    res.send(500, "There was an error.");
});

Notice that the function has 4 parameters, as opposed to 3 normally. Now, when your app runs and you do this:

next(new Error("Some error"));
return;

Then your error handler is called.

What you're doing now is basically repeating your error handling code ("send status 401") in every normal route. There are off the shelf loggers such as Morgan.

RickN
  • 12,537
  • 4
  • 24
  • 28
  • I am not sure I understand your explanation. I should clarify I am particulary interested in what next is doing, I know it is a anti-blocking, anti-boxing strategy. I will look into Morgan, thanks. – Stephan Kristyn Sep 26 '14 at 22:22