express-session使用时 req.session undefined和session.id输出问题

express-session使用时 req.session undefined问题

TypeError: Cannot set property ‘user_id’ of undefined

在学习session过程中,往req.session属性赋值时总是报以上的错误,

app.use('/city', cityRouter);
app.use('/language', languageRouter);
app.use('/register', registerRouter);
app.use('/login', loginRouter);
// session 配置
var session = require("express-session")
app.use(session({
     
    secret: "dfjdlfajdfafdafadfadfaf",
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 },
    resave: true,
    saveUninitialized: true
}))

把session写在路由下面就会报错:TypeError: Cannot set propert
解决办法很简单,将session写再路由上面就阔以啦

// session 配置
var session = require("express-session")
app.use(session({
     
    secret: "dfjdlfajdfafdafadfadfaf",
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 },
    resave: true,
    saveUninitialized: true
}))

app.use('/city', cityRouter);
app.use('/language', languageRouter);
app.use('/register', registerRouter);
app.use('/login', loginRouter)

还有就是request.session.id = stateResult[0].user_id;这种将一个值赋给session.id

 if (request.body.password == stateResult[0].password) {
     
            request.session.id = stateResult[0].user_id;//这里赋值为2
            console.log(request.session.id)
            response.json({
     
                code: 200,
                message: "登录成功!"
            })

输出为:BRpabyVXg1fVfpKGQeCb9QxPH_IL-KD-
BRpabyVXg1fVfpKGQeCb9QxPH_IL-KD-
查了下哈资料发现id属性是session本身就有的所以出现这种错误。

整改后:

  if (request.body.password == stateResult[0].password) {
     
            request.session.user_id = stateResult[0].user_id;
            console.log(request.session.user_id)
            response.json({
     
                code: 200,
                message: "登录成功!"
            })

输出为:2
在这里插入图片描述
。。。。。。。。

你可能感兴趣的:(node.js,javascript)