快速会话无法设置未定义的 属性 'id'

express session Cannot set property 'id' of undefined

var redis = require('redis');
var router = express.Router();
var mysql = require('mysql');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var client  = redis.createClient();
var session = require('express-session'),
RedisStore = require('connect-redis')(session);
var app = express();
app.use(cookieParser);
app.use(session({
    store : new RedisStore({
    host:'localhost',
    port:7351,
    maxAge: 300000,
    client:client,
    ttl:260
   }
 ),
 secret:'dafdsa',
resave:false,
saveUninitialized:true,
}));

这是我的设置,这是我的代码

router.post('/', function(req, res, next) {
  var id = req.body.userid;
  var passwd = req.body.password;
  var sess = req.session;
  var login_chk = pool.getConnection(function(err,connection){
      connection.query('SELECT U_passwd FROM Member WHERE U_id = ?',[id],function(err,row,req){
         if(err)console.log(err);
      var sqlpasswd = row[0].U_passwd;
      var answer = 0;
      answer = passwd_chk(passwd,sqlpasswd);
      if(answer ===1){
          save_session(id);
          res.render('main');
      }


var save_session = function(req){
    req.session.id = req; 
}

我将 post(登录)并在会话中保存 ID,但此代码总是错误,无法设置 属性...我该如何解决?... 谢谢回答

发生这种情况是因为您将 userId 作为 save_session(req) 参数传递。然后你在你的情况下做 req.session.id = req;userId.session.id = userId; 相同。该错误通知您 userId 没有 session 属性(显然)。您只需要将 requserId 作为参数传递即可。像这样更改您的代码。

router.post('/', function(req, res, next) {
  var id = req.body.userid;
  var passwd = req.body.password;
  var sess = req.session;
  var login_chk = pool.getConnection(function(err,connection){
      connection.query('SELECT U_passwd FROM Member WHERE U_id = ?',[id],function(err,row,req){
         if(err)console.log(err);
      var sqlpasswd = row[0].U_passwd;
      var answer = 0;
      answer = passwd_chk(passwd,sqlpasswd);
      if(answer ===1){
          save_session(req,id);        <--- Change this
          res.render('main');
      }


var save_session = function(req,id){   <--- Change this
    req.session.id = id;               <--- Change this
}

希望对您有所帮助。