Ok for some reason the session flash works when I res.render(), but when I try to set the session flash and then redirect, it doesn't display. The problem is below in the contact method in the else clause)...
This is what is logged to the console during the redirect:
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{ info: [ 'Thanks we will return your message soon' ] }
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
As you can see, the message is definitely in there, but it looks like it's getting replaced with an empty object.
Here is my code:
app.js
var flash = require('connect-flash');
// Grab sessions
var sessionFlash = function(req, res, next) {
res.locals.messages = req.flash();
console.log(res.locals.messages);
next();
}
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(viewHelpers());
app.use(express.bodyParser({ uploadDir : './' }));
app.use(expressValidator);
app.use(express.methodOverride());
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({
secret: config.secret,
cookie: {
maxAge: 365 * 24 * 60 * 60 * 1000
},
store: new MongoStore(config.db)
}));
app.use(flash());
app.use(sessionFlash);
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
views/layout.jade
- if (typeof message !== 'undefined')
=message
controllers/index.js
function controllers(params) {
controllers.contact = function(req, res) {
if (errors) {
// This works as intended
req.flash('info', 'Please fix the errors below.');
res.render('contact', {
title : 'Contact -',
message: req.flash('info'),
errors: errors,
params: params
});
return;
} else {
// This doesn't work
req.flash('info', 'Thanks we will return your message soon');
res.redirect('/');
}
};
return controllers
}
module.exports = controllers;
Well, you are redirecting to '/', which server does not respond to.
You don't have app.get('/', function(req, res){...}); in your app.js
Flash messages are messages that are stored on the server for the duration between two requests from the same client, and thus are only available in the next request. The flash does not show because your res.redirect('/'); does nothing.