node.js开发错误——TypeError: Cannot set property 'XXX' of undefined

在设置express-session时出现该错误。

原因:中间件app.use(session());放的位置不对。

要把session设置的中间件放在路由控制器之前。

正确位置:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ejs = require('ejs');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');

var routes = require('./routes/index');
var settings = require('./settings');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html',ejs.__express);
app.set('view engine', 'html');



// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//session
app.use(session({
  secret:settings.cookieSecret,            //用来防止篡改cookie
  key:settings.db,                        //cookie的名字
  cookie:{maxAge:1000*60*60*24*30},       //30天
  store: new MongoStore({
    db:settings.db,
    host:settings.host,
    port:settings.port,
    url: 'mongodb://localhost/blog'
  }),
  resave:true,
  saveUninitialized:false
}));

//flash
app.use(flash());
//设置flash
app.use(function(req, res, next){
  res.locals.error = req.flash('error') || "";
  res.locals.success = req.flash('success') || "";
  next();
});

routes(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});






module.exports = app;


你可能感兴趣的:(node.js)