Search code examples
javascriptnode.jsexpressinitializationconnect-flash

req.flash is not a function - Initialization order


I am using node.js with Express 4. I have problem with connect-flash initialization. I looked at many questions with different answers and I still can't solve my problem. I tried many combinations of app.use() order and still getting TypeError req.flash is not a function

Here is my current initialization order:

var app = express();
var index = require('./routes/index');
var users = require('./routes/users');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(sassMiddleware({
    src: __dirname + '/public/sass',
    dest: path.join(__dirname, 'public/css'),
    debug: true,
    outputStyle: 'compressed',
    prefix:  '/css'
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));
app.use(i18n({
  translationsPath: path.join(__dirname, './locales'), 
  siteLangs: ["es","en"]
}));
app.use(function (res,req,next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
});

app.use('/', index);
app.use('/users', users);
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
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');
});

Thank you for your help.


Solution

  • app.use(function (res,req,next) {
        //...
    })
    

    Your req and res parameters in this function is in the wrong order.