脸书authentication与护照。 无法读取未定义错误的属性“0”

我正在学习使用Facebook将社交authentication添加到应用程序中。 一切工作正常,直到我真的尝试login到我的testing应用程序与Facebook。 而不是路由到configuration文件页面,我得到这个错误:

Cannot read property '0' of undefined TypeError: Cannot read property '0' of undefined at Strategy.generateOrFindUser [as _verify] (C:\projects\Side Projects\passyapp\app.js:16:19) at C:\projects\Side Projects\passyapp\node_modules\passport- oauth2\lib\strategy.js:193:24 at C:\projects\Side Projects\passyapp\node_modules\passport- github\lib\strategy.js:174:7 at passBackControl (C:\projects\Side Projects\passyapp\node_modules\oauth\lib\oauth2.js:134:9) at IncomingMessage.<anonymous> (C:\projects\Side Projects\passyapp\node_modules\oauth\lib\oauth2.js:157:7) at emitNone (events.js:91:20) at IncomingMessage.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9) 

下面是从我的APP.JS文件中的一个SNIPPET:

 function generateOrFindUser(accessToken, refreshToken, profile, done){ if(profile.emails[0]) { User.findOneAndUpdate( { email: profile.emails[0] }, { name: profile.displayName || profile.username, email: profile.emails[0].value, photo: profile.photos[0].value }, { upsert: true }, done ); } else { var noEmailError = new Error("Your email privacy settings prevent you from signing in."); done(noEmailError, null); } } passport.use(new FacebookStrategy({ clientID: process.env.FACEBOOK_APP_ID, clientSecret: process.env.FACEBOOK_APP_SECRET, callbackURL: "http://localhost:3000/auth/facebook/return", profileFields: ['email', 'id', 'displayName', 'photos'] }, generateOrFindUser) ); //in order for passport to handle sessions you need to implement the two methods //directly below passport.serializeUser(function(user, done) { done(null, user._id); }); passport.deserializeUser(function(userId, done) { User.findById(userId, function(err, done) { //done(err, user); }); }); 

这是我的用户架构

 var UserSchema = new mongoose.Schema({ email: { type: String, required: true, trim: true, unique: true, }, name: { type: String, required: true, trim: true, }, favoriteBook: { type: String, required: false, trim: true }, photo: { type: String, required: true, trim: true } }); 

我希望这不是浪费你忙碌的编码时间。 任何尝试帮助是非常感激的。

编辑:更好的答案

我猜这是profile.emails对象(不能告诉基于行号,因为你的代码是一个片段)。 在这个函数之前,你应该看起来像这样的代码。

你需要确保两件事情:

1.当您调用passport.authenticate ,请确保请求电子邮件范围,如下所示: app.route('/auth/facebook').get(passport.authenticate('facebook', { scope: ['email']}));

2。

 passport.use(new FacebookStrategy({ clientID: facebookConfig.clientID, clientSecret: facebookConfig.clientSecret, callbackURL: facebookConfig.callbackURL, profileFields : ['id', 'name', 'email'], }, function generateOrFindUser... 

您的profileFields数组包含电子邮件是非常重要的。