在Express.js中将variables从中间件传递给Passport

我想通过一个variables中间件,并成功使用Facebook的护照成功后可用。

// route for facebook authentication and login router.get('/connect/facebook', rentalinfo, passport.authenticate('facebook', { scope : 'email' })); // handle the callback after facebook has authenticated the user router.get('/connect/facebook/callback', passport.authenticate('facebook', { //successRedirect : '../../../protected', failureRedirect : '/' }), function(req, res) { // successful auth, user is set at req.user. redirect as necessary. //Get the redirect location from the response //console.log(req.body); console.log(req.bookingarray); res.redirect('/protected'); }); 

我的中间件:

 //Rent item middleware - carries rental info through signup/login process function rentalinfo(req, res, next){ //console.log('MIDDLEWARE VARIABLE: '+ bookingarray); req.bookingarray = 'SOMETHING'; //return bookingarray; //if (something(res)) redirect('http://google.com'); // no access to your site next(); // go to routes }; 

然后我尝试在我的Facebook护照策略中访问它。

 passport.use(new FacebookStrategy({ // pull in our app id and secret from our auth.js file clientID : configAuth.facebookAuth.clientID, clientSecret : configAuth.facebookAuth.clientSecret, callbackURL : configAuth.facebookAuth.callbackURL, profileFields : ["emails", "displayName"], // this allows us to pass in the req from our route (lets us check if a user is logged in or not) passReqToCallback : true }, // facebook will send back the token and profile function(req, token, refreshToken, profile, done) { console.log(req.bookingarray); // asynchronous process.nextTick(function() { // check if the user is already logged in if (!req.user) { ... } } })); 

但是它只是返回未定义。 我试过了,我错过了什么? 目的是在authentication之前和之后保持用户的状态。

你需要把这个存储在用户会话中,而不是只有一个请求生命周期的请求。 你的第二条路线是由Facebook调用的FBcallback,因此rentalinfo中间件不会被调用,因此没有variables。

如果你不想使用会话(例如,无状态的REST API),那么你需要修改你的中间件来检查用户是否被authentication。 这是否适合你将取决于你的情况。