我正在尝试将变量传递给中间件,并在使用facebook-passport成功验证后可用。
// 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) {
...
}
}
}));
然而它只是以未定义的方式返回。我试过了,我错过了什么?目的是在身份验证之前和之后保持用户的状态。
答案 0 :(得分:1)
您希望将其存储在用户会话中,而不是具有一个请求生存期的请求中。你的第二条路线是由Facebook调用的FB回调,因此rentalinfo
中间件不会被调用,因此没有你的变量。
如果您不想使用会话(即无状态REST API),那么您需要修改中间件以检查用户是否已经过操作并从那里开始。这是否适合您将取决于您的方案。