简体   繁体   中英

Passport-facebook returns undefined fields except id and displayName

I have been using this:

Scopes ['email', 'public_profile']

Fields ['emails', 'id', 'displayName', 'name', 'photos']

Does anybody resolved this problem? I have read a lot of answers here. But no one works for me or they are outdated (around 2012/13 year)

Just a default passport code:

// Configure Facebook auth Strategy
// ==================================================================
passport.use(new FacebookStrategy({
  clientID: CONFIG.facebook.id,
  clientSecret: CONFIG.facebook.secret,
  callbackURL: `${CONFIG.url}/${CONFIG.routes.auth}/facebook-token`,
  fields: ['emails', 'id', 'displayName', 'name', 'photos']
}, (accessToken, refreshToken, profile, cb) => {
  console.log(profile, accessToken, refreshToken);
  Account
    .findOne({'facebook.id': profile.id})
    .then(account => {
      if (account) {
        cb(null, account);
      } else {
        // Sign up data to profile
      }
    })
    .catch(err => cb(err));
}));

And apropriate routes:

  // Route to request Facebook token
  // ==================================================================
  router.get(`/${URL}/facebook`, passport.authenticate('facebook', {failWithError: true, scope: ['email', 'public_profile']}));

  // Route to recieve Facebook data
  // ==================================================================
  router.get(`/${URL}/facebook-token`, passport.authenticate('facebook', {failWithError: true}), (req, res) => {
    console.log('Facebook', req.session, req.user, req.account);
  });

What specific fields are you looking for?

email is actually profile.emails which is an array so you have to use an index to get the default

profile.emails[0]

and the name is actually another object

profile.name.givenName

profile.name.familyName

profile.name.middleName

You could use util to print the profile object to the console to see the fields

import util from 'util';

console.log(util.inspect(profile, {showHidden: false, depth: null}))

When you print you would also find the raw json from the facebook response which is

_json

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