2017-12-27 315 views
0

在PassportJS Google OAuth策略中,出于一些奇怪的原因,当我序列化用户标识并将其发送到cookie以发送到浏览器时,它不会返回该标识以反序列化它,我是因为当我console.log用户,它返回undefinedpassportjs google oauth2策略

passport.deserializeUser((id, done) => { 
    User.findById(id).then((user, done) => { 
     console.log(user); 
     done(null, user); 
    }); 
}); 

详谈我的cookie被下面

app.use(cookieSession({ 
    maxAge: 24 * 60 * 60 * 1000, 
    keys: 'dkfehfhgddf' 
})); 
+0

您使用的猫鼬来从MongoDB的用户数据? –

+0

是啊我do.use mongodb –

回答

0

在你使用的猫鼬的情况下,你已经在你的代码中的错误,这是导致意想不到的行为。

如果您尝试使用findById()函数的Promise版本,则必须事先调用.exec(),以便分派该操作。此外,你已经隐藏了deserializeUserdone回调,所以它永远不会被调用。

下面是它如何工作:

passport.deserializeUser((id, done) => { 
    User.findById(id).exec() 
    .then(user => { 
     if (user) {// user may be null 
     done(null, user); 
     } else { 
     done(new Error("User not found"), null); 
     } 
    }) 
    .catch(error => { 
    done(error, false); 
    }); 
}); 
+0

感谢您的澄清。好吧,当我的console.log这个id返回给mongo时,它从浏览器中不会返回任何东西。因此数据库甚至没有收到id来查询它 –