javascriptnode.jsredisexpress-session

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,
}));

this is my setting and this is my code

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; 
}

i will post (login) and i save id in session but this code is always err to cannot set property... how can i fix it?... thanks for answer


Solution

  • This happens cause you're passing userId as save_session(req) argument. Then you're doing req.session.id = req; in your case the same as userId.session.id = userId;. The error notices you that userId has not session property (Obsiously). All you need is pass req and userId as arguments. Change your code like this.

    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
    }
    

    I hope It helps.