在Express JS中访问用户信息返回Undefined

时间:2018-11-13 18:59:38

标签: javascript node.js express authentication

我当前正在使用Passport在我的应用程序中进行身份验证。当尝试提取用户电子邮件以将其与其他信息一起存储在数据库中时,我得到的返回值是undefined。如果拉出整个用户对象,我将获得正确的信息。见下文。

这是初始化会话的server.js文件。

app.use(session({
    secret: 'sessionSecret'
})); 
app.use(passport.initialize());
app.use(passport.session()); 
app.use(flash());

这是路线信息

app.get('/itemCreation', function (req, res) {
    res.render('itemCreation.ejs', {
        user: req.user 
    });
});
app.post('/itemCreation', function (req, res) {
    var item = new itemSchema();
    item.local.productName = req.body.productName;
    item.local.itemPrice = req.body.itemPrice;
    item.local.Quantity = req.body.Quantity;
    item.local.Description = req.body.Description;
    console.log(req.user.firstName);
    item.save(function (err) {
        if (err)
            throw err;
        else
            console.log('Saved item information successfully');

    });
    res.redirect('/shop');
});

这是我的物品模型

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');

var itemSchema = mongoose.Schema({

    local            : {
        productName     : String,
        itemPrice       : Number,
        Quantity        : Number,
        Description     : String
        }

});

module.exports = mongoose.model('item', itemSchema);

Here is the result of pulling the whole object,我通过致电获得

console.log(req.user);

and here is the result of pulling just the email from the object,我可以通过致电

获得
console.log(req.user.email);

1 个答案:

答案 0 :(得分:0)

应该为console.log(req.user.local.email);