简体   繁体   中英

How does the Passport custom callback work?

I don't understand this example

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

What I see happening here is

app.get('path', function(req, res, next) {/*bunch of code*/})(req, res, next)

How can this work since it is not a reference to a function that is placed behind (req, res, next) ?

Your simplified example is a little off, probably due to mismatching brackets and such...

If I reduce the "official" passport example for custom callbacks, I get:

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
  })(req, res, next);
});

So my first assumption is that (req, res, next) are being passed to a express-middleware-compliant function returned from passport.authenticate .

If I go poke around the authenticate code on GitHub , around line 81 or so (as of this writing) it looks like that's just what's happening starting with:

return function authenticate(req, res, next) {
    /* lots and lots of lines follow */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM