javascript - Redirect if session is not available node.js -


i trying write code route if session.user_id undefined redirect home page. reason redirect doesnt execute , mysql condition fired , crashes server because session.user_id undefined , cant load game without data.

is there way use universal redirect on routes if session not available redirect login?

                router.get('/game', function(req,res) {                  console.log(req.session.user_id);                  if (req.session.user_id === "undefined") {                  res.redirect('/');                  }else {                  var condition = 'userid = ' + req.session.user_id;                  projectx.allgamedata(condition, function(data){                  var hbsobject = {heroes : data, logged_in: req.session.logged_in, isuser: req.session.isuser, isadmin: req.session.isadmin}                  res.render('game', hbsobject);                  });                  };                  }); 

you should either use: if (req.session.user_id === undefined)

or if ( typeof req.session.user_id === "undefined")

apart that, it's better have middleware function checks user session. way, can insert call middleware in routes, require user logged in:

router.get('/game', checkusersession, function(req,res) {   // code here });  function checkusersession( req, res, next ) {     if( req.session.user_id )     {         next();     }     else     {         res.redirect('/homepage');     } }//checkusersession() 

Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -