Search code examples
node.jsexpresspassport.jsmiddleware

What the difference between these two programs segments


When I try to create a middleware 'Passport' then this issue occurs.

This Program segment works good:

router.post('/login',function(req,res,next) {
   passport.authenticate('local', function(err,user,message){
      res.send(message.message);    
   }) (req, res, next);
});

But when I changed this to:

router.post('/login', function (req, res, next) {
  passport.authenticate('local',(err, user,message) => {
    res.send(message.message);  
  });
}, function(req, res, next){

});

The post request doesn't end. Loading doesn't stop.

What's the difference between these code snippets? I think both programs are the same.


Solution

  • passport.authenticate() returns a middleware function. So in the first snippet, what you are doing is,

    router.post('/login',function(req,res,next) {
      var middleware = passport.authenticate('local',(err, user,message) => {
        res.send(message.message);  
      }); // middleware is now a function. You can call it!
    
      middleware(req, res, next);
    });
    


    In the second snippet, the middleware function which is returned is never used. Thus, your (err, user,message) => {} is never executed.

    And that is why the request does not end.

    Try:

    router.post('/login', passport.authenticate('local', function(err,user,message) {
      res.send(message.message);    
    }));