express 会话无法设置未定义的属性“id”

问题描述 投票:0回答:2
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; 
}

我将发布(登录)并在会话中保存ID,但此代码总是错误地无法设置属性...我该如何修复它?... 谢谢你的回答

javascript node.js redis express-session
2个回答
1
投票

发生这种情况是因为您将

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

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
}

我希望它有帮助。


0
投票

回答太晚了,但也许其他人可以使用这个答案。

req.session.id 是保留的,因此您不能将会话命名为“id”,给它另一个名称即可。

© www.soinside.com 2019 - 2024. All rights reserved.