julekgwa julekgwa - 12 days ago 3
Javascript Question

req.flash is not a function Nodejs

I have been staring at this code for the past hour and I don't know how to fix the problem, I'm getting

'TypeError: req.flash is not a function
. I have tried moving
app.use(flash)
around and still I'm getting the error. How can I fix this?

var flash = require('connect-flash');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var handlebars = require('express-handlebars').create({
layoutsDir: path.join(__dirname, "views/layouts"),
partialsDir: path.join(__dirname, "views/partials"),
defaultLayout: 'layout',
extname: 'handlebars'
});
var expressValidator = require('express-validator');
var session = require('express-session');
var passport = require('passport');
var localStrategy = require('passport-local').strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/login');
var db = mongoose.connection;

// init app
var app = express();

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

// view engine
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, "views"));

app.use(expressValidator());

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

// set static folder
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);

app.use(flash);

// express session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));

// passport init
app.use(passport.initialize());
app.use(passport.session());

// Global Vars
app.use(function (req, res, next) {
res.local.success_msg = req.flash('success_msg');
res.local.error_msg = req.flash('error_msg');
res.local.error = req.flash('error');
next();
});

// set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function () {
console.log('Server started on port ' + app.get('port'));
});

Answer

The middleware you set up with app.use() is being executed in the order it's declared, so in your case the flash-module will be called before session-handeling. A quick look into the connect-flash-docs reveals that app.use(flash()); should be called after the other session-related middleware is setup, so try moving it down some lines, that should fix your problem.

Quote from the connect-flash-docs:

Flash messages are stored in the session. First, setup sessions as usual by enabling cookieParser and session middleware. Then, use flash middleware provided by connect-flash.

Comments