简体   繁体   中英

TypeError: Cannot read property '0' of undefined passport-facebook

Whenever I try to login using facebook, it will return this error, i have followed this link advise but still no luck. Passport-facebook doesn't get email

newUser.facebook.email = profile.emails[0].value;
                                           ^
TypeError: Cannot read property '0' of undefined    

Here's the code

var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var User = require('../models/user');

var facebookConfig = {
  clientID: 'ID',
  clientSecret: 'SECRET',
  callbackURL: 'http://localhost:8080/facebook/callback'
};

var facebookInit = function(token, refreshToken, profile, callback) {
  User.findOne({ "facebook.id": profile.id }, function(err, user) {
    if (err) return callback(err);

    if (user) {
      return callback(null, user);
    }

    var newUser = new User();
    newUser.facebook.id = profile.id;
    newUser.facebook.token = token;
    newUser.facebook.email = profile.emails[0].value;
    newUser.facebook.displayName = profile.displayName;
    newUser.facebook.photo = profile.photos[0].value

    newUser.save(function(err) {
      if (err) {
        throw err;
      }
      return callback(null, newUser);
    });
  });
}

passport.use(new FacebookStrategy(facebookConfig, facebookInit));

passport.serializeUser(function(user, callback) {
  callback(null, user.id)
});

passport.deserializeUser(function(id, callback) {
  User.findById(id, function(err, user) {
    callback(err, user);
  });
});

module.exports = {
  facebookLogin: passport.authenticate("facebook",  { scope: ['email'] }),
  facebookCallback: passport.authenticate("facebook", {
    successRedirect: "/profile",
    failureRedirect: "/"
  })
}

I tried to change the scope from { scope: 'email' } to { scope: ['email'] } , still no luck.

Did you try explicitly specify email field in your config? In your case it should be:

var facebookConfig = {
  clientID: 'ID',
  clientSecret: 'SECRET',
  callbackURL: 'http://localhost:8080/facebook/callback',
  profileFields: ['id', 'email', 'gender']
};

Pay attention to profileFields , seems like it's required by APIv2.4. That should help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM