0
点赞
收藏
分享

微信扫一扫

使用req.session.xxx时出现 Cannot set property ‘xxxx‘ of undefined


问题如下

使用req.session.xxx时出现 Cannot set property ‘xxxx‘ of undefined_中间件

查看app.js 代码发现引入的session模块 为灰色没有使用

使用req.session.xxx时出现 Cannot set property ‘xxxx‘ of undefined_session_02

查看express-session中的​​官方文档​​其中req.session使用案例为:

// Use the session middleware
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))

// Access the session as req.session
app.get('/', function(req, res, next) {
if (req.session.views) {
req.session.views++
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' + req.session.views + '</p>')
res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
req.session.views = 1
res.end('welcome to the session demo. refresh!')
}
})

发现没有配置session的中间件

app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))

固配置中间件

// 配置session的中间件
app.use(session({ secret: 'secret key' }));

运行结果显示正常:

使用req.session.xxx时出现 Cannot set property ‘xxxx‘ of undefined_session_03


举报

相关推荐

0 条评论