这是我的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: "获取全部课程"
})
}
}
答案 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"
})