req.session is undefined in Node?

2019-07-22 08:09发布

问题:

I already looked at the other answers for similar questions, yet none of them worked for me. I two pieces of code, one to test that cookies were working(cookieTest.js), and one to actually use them(users.js). I tried moving the app.use() statements for the session middleware and the cookie middleware to no avail. Any ideas on how to fix this?

users.js

//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')
var User = require('../models/user.js');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
//Express Setup
var express = require('express');
var router = express.Router();
var app = express();
var expressValidator = require("express-validator");
var session = require('express-session');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: '_secret_', cookie: { maxAge: 60 * 60 * 1000 }, saveUninitialized: false, resave: false}))
//Routes
router.get('/register', function(req, res){
  res.sendFile(appDir + "/views/register.html");
})
router.post('/register', function(req, res) {
  req.check('name', 'Name must be Filled in').notEmpty();
  req.check('email', 'Email must be Filled in').notEmpty();
  req.check('email', "Invalid Email").isEmail();
  req.check('password', 'Password Field must be Filled in').notEmpty();
  req.check('password', 'Passwords do not Match').equals(req.body.password2)
  var errors = req.validationErrors();
  if(errors) res.send(errors)
  else{
    var newUser = new User({
      name: req.body.name,
      email: req.body.email,
      password: req.body.password,
      info: req.body.user_bio
    });
    User.createUser(newUser, function(err, user){
            if(err) throw err;
    });
    res.redirect('../')
  }
})
router.get('/login', function(req, res){
  res.sendFile(appDir + "/views/login.html");
})
router.post('/login', function(req, res){
  var email = req.body.email;
  var candidatePass = req.body.password;
  User.findOne({ 'email': email }, 'password id', function (err, user) {
    if (err) return handleError(err);
    User.checkPassword(candidatePass, user.password, function(err, isMatch){
      if(err) throw err;
      if(!isMatch) res.end('Password Incorrect!');
      else{
        req.session.userId = user.id;
        res.redirect('../');
      }
    })
  })
})
//Exports
module.exports = router;

When I run this I get the error TypeError: Cannot set property 'userId' of undefined, which means that req.session is undefined. However, when I run this, it works fine

var express = require('express');
var session = require('express-session');
var app = express();
var uuid = require('node-uuid');
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Use the session middleware
app.use(session({
  secret: 'jaredasch',
  cookie: { maxAge: 60 * 60 * 1000 },
  saveUninitialized: false,
  resave: false
}))

// Access the session as req.session
app.get('/', function(req, res, next) {
  var sess = req.session
  if (sess.uuid) {
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>Session UUID: ' + sess.uuid + '</p>');
    res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
    res.write('<form method = \'POST\'action = \'/\'><button type = \'submit\'></form>');
    res.end()
  } else {
    sess.uuid = uuid.v4();
    res.setHeader('Content-Type', 'text/html');
    res.write('Set Up Session \n')
    res.write('<p>Session UUID: ' + sess.uuid + '</p>');
    res.end('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
  }
})

app.post('/', function(req,res){
  req.session.destroy(function(err) {
    if(err) throw err;
    console.log('Session Destroyed')
  })
  res.redirect('/');
})

app.listen(3000, function(){
  console.log('Listening on Port 3000')
});

Why does this work and the one above not, and how could I fix the one above? How would you reccomend fixing such an issue?

回答1:

Try using app.use(cookieParser("_secret_")); so that its the same secret as with Express