2017-12-27 313 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來查詢它 –