Cannot get properties of req.user

2019-09-04 14:32发布

问题:

I'm using Passport to auth My projec. After successful auth, users are directed to "/home".At this point, the request has the user object. However, once I redirect, the req.user.email is undefined. :'(

 exports.test= function (req, res) {
    console.log(req.user);    
    console.log(req.user.id);
    console.log(req.user.email);

}

the terminal display :

ModelBase {
      attributes:
       { id: 18,
         first_name: 'test',
         last_name: 'test',
         email: 'test1@gmail.com',
         password: '18fa9883b74578494b578048273e66d2edbf57b6',
         active: 1,
         created: Mon Oct 17 2016 08:15:58 GMT+0700 (SE Asia Standard Time),
         modified: Thu Nov 17 2016 10:59:00 GMT+0700 (SE Asia Standard Time),
         salt: '140996000870',
         Balance: 0,
         ExpireDate: Mon Apr 02 2018 00:00:00 GMT+0700 (SE Asia Standard Time),
         used: 0,
         donate: 1 },
      _previousAttributes:
       { id: 18,
         first_name: 'test',
         last_name: 'test',
         email: 'test1@gmail.com',
         password: '18fa9883b74578494b578048273e66d2edbf57b6',
         active: 1,
         created: Mon Oct 17 2016 08:15:58 GMT+0700 (SE Asia Standard Time),
         modified: Thu Nov 17 2016 10:59:00 GMT+0700 (SE Asia Standard Time),
         salt: '140996000870',
         Balance: 0,
         ExpireDate: Mon Apr 02 2018 00:00:00 GMT+0700 (SE Asia Standard Time),
         used: 0,
         donate: 1 },
      changed: {},
      relations: {},
      cid: 'c1',
      id: 18,
      _knex: null }
18
undefined

回答1:

Because in the JSON being fetched email is not a top level key. Its within attributes key. Try with console.log(req.user.attributes.email); .



回答2:

use "req.user.attributes.email" instead of "req.user.email"



回答3:

I had the same issue, I wanted to iterate over all the attributes of the user object.

Turns out the req.user object is not a normal one, and the attributes are actually inside req.user._doc

So you can iterate over the attributes like this:

Object.keys(req.user._doc).forEach(function(each_attribute){
  console.log('each_attribute', each_attribute)
})

I hope it helps.