在Node中未定义req.session?

时间:2016-05-31 02:15:54

标签: javascript node.js session express session-cookies

我已经查看了类似问题的其他答案,但它们都没有为我工作。我有两段代码,一块用于测试cookie正在运行(cookieTest.js),另一块用于实际使用它们(users.js)。我尝试移动会话中间件和cookie中间件的app.use()语句无济于事。关于如何解决这个问题的任何想法?

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;

当我运行此操作时,我收到错误TypeError: Cannot set property 'userId' of undefined,这意味着req.session未定义。但是,当我运行它时,它工作正常

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

为什么这项工作和上面的工作没有,我怎么能修复上面的那个?你会如何推荐解决这个问题?

1 个答案:

答案 0 :(得分:0)

尝试使用app.use(cookieParser("_secret_"));,使其与Express

具有相同的秘密