Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
Unable to retrieve session variable after setting it

I am setting my session variable to true whenever username and password is correct in my post function.But when I am unable to retrieve my session in my responses function. when I console it, it says undefined.

var session = require('express-session')
var userSchema = new Schema({
  name: String,
  age: Number,
  gender: String,
});
var users = mongoose.model('users', userSchema)
/* GET home page. */
router.post('/login', function(req, res, next) {
var username = req.body.username;
var password = req.body.password;
if(username == "tina" && password == "123456")
{
req.session.login = true;
console.log("session1:" + req.session.login);
setTimeout(function(){ res.redirect("/responses"); }, 3000);
}
else{
res.redirect("/loginerror");
}

});


router.get('/responses', function(req, res, next) {
//if(req.session.login==true){
console.log("session2:" + req.session.login);
users.find({}, function(err,users) {
  if (err) {
  console.log( err);
  throw err;
}
 else{
 console.log("session3:" + req.session.login);
 if(req.session.login){
 console.log("111");
   res.render('responses', { title: 'responses',users:users });
}
 else{
 res.redirect("/loginerror");
}
  }
})
//}


});

router.get('/loginerror', function(req, res, next) {
  res.render('loginerror', { title: 'loginerror' });

});

router.get('/', function(req, res, next) {
  res.render('index', { title: '',users:users });

});

module.exports = router;
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You haven't setup your express session properly. Just using the below line is not enough.

var session = require('express-session');

The express app needs to be made to use this session.

var session = require('express-session')

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}))

Do the above in your app.js/server.js

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!