为什么我无法获得会话的价值?

时间:2017-04-19 13:47:26

标签: node.js mongodb express

这是我的app.js代码,我在mongoDB中保存会话。

    const cookieParser = require('cookie-parser');
    const cookieSession = require('cookie-session');
    const session = require('express-session'); 
    const mongoStore = require('connect-mongo')(session);
    const db = mongoose.connect("mongodb://localhost/course");
    app.use(cookieParser()); 
    app.use(cookieSession({ //session
       secret: "system",
       store: new mongoStore({
           mongooseConnection: db.connection,
           collection: "sessions"
    })
}))

当我想获得req.session.user时,我得到了未定义。 但是我在用户登录时保存会话。

    exports.fetchCourse = async (req, res) => {
    console.log("session is: " + req.session.user);
    if(req.session.user) {
        const user = await User.findOne({_id: req.session.user._id}).populate("course");
        console.log("course are: " + user.course.length);
        res.status(200).send({
            code: 1,
            data: user.course,
            msg: "获取全部课程"
        })
    }
}

1 个答案:

答案 0 :(得分:0)

您使用cookieSession代替expressSsession

根据docs,您的代码应与此类似(如果您使用快递4及以上):

 const session = require('express-session'); 
 const mongoStore = require('connect-mongo')(session);
 const db = mongoose.connect("mongodb://localhost/course");




app.use(session({
       secret: "system",
       store: new mongoStore({
           mongooseConnection: db.connection,
           collection: "sessions"


 })