Forget
Forget

Reputation: 152

'TypeError: req.flash is not a function' with app.use(flash()); and still not working

The error occrus on my routes.js:

app.get('/login', function(req, res) {
    // render the page and pass in any flash data if it exists
    res.render('login.html', { message:  req.flash('loginMessage') }); 
});

On the req.flash to be more specific.

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

//PASSPORT AUTH
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

As you can see I have app.use(flash()); which was the most common error on the other cases.

Flash is initialized at the beginning as such:

var flash = require('connect-flash');

I really don't see where the problem is.

EDIT: ERROR PAGE:

error

Upvotes: 0

Views: 4662

Answers (1)

bolav
bolav

Reputation: 6998

This should work. Did you try to create a minimal test case? Your problem is probably somewhere else in the code. Maybe app.use(flash()) is not being run?

var flash = require('connect-flash');
var express = require('express')
var session = require('express-session')
var app = express();

app.use(flash());
app.use(session({ secret: 'keyboard cat' }))

app.get('/flash', function(req, res){
  req.flash('info', 'Flash is back!')
  res.redirect('/');
});

app.get('/', function(req, res){
  res.send(req.flash('info'));
});

app.listen(3000);

Upvotes: 1

Related Questions