In Express.js, how do I get my template to display flash messages?

app.get('/',function(req,res){ res.render('home'); // I want the template to be able to access the flash message.. }); app.get('/go',function(req,res){ req.flash("info", "You went GO, and got redirected to home!"); res.redirect('/'); }); 

First, the user goes to "/ go". After that, it will be redirected to "/", and I want the flash message to display as a javascript warning.

How can i do this?

+4
source share
6 answers

Add it as local to your call for rendering:

 res.render("home", {info: req.flash("info")}); 

And use it in your template:

 #flash p= info 
+10
source

You can use express dynamic assistants to make your life easier.

 app.dynamicHelpers({flashMessages: function(req, res) { var html = "" , flash = req.flash(); ['error', 'info'].forEach(function(type) { if(flash[type]) { flash[type].forEach(function(message) { html += "<div class='alert " + type + "'>" + message + "</div>"; }); } }); return html; }}); 

and in your layout (ejs example)

  <body><%- flashMessages %><%- body %></body> 
+6
source
 app.dynamicHelpers({flash: function(req, res){return req.flash();}}); 

You now have access to the flash object in your view. There is no HTML in your logic and you do not need to add all parameters to all routes.

+4
source

For me, I use the following code to display a flash message:

In app.js

 app.use(function (req, res, next) { req.session.message = req.session.message || { error: [], success: [], info: [] }; app.locals.message = req.session.message; } 

In your user.js route:

 app.post('/users/new', function (req, res, next) { //... // do some work req.session.message.info.push('Account created successfully'); res.redirect('/login'); }); 

Then create message.jade so you can be included in other views:

In message.jade

 - var i - if (message.error && message.error.length) .alert.alert-warning.alert-dismissable button.close(type="button", data-dismiss="alert", aria-hidden="true") &times; - for (i = 0; i < message.error.length; i++) .center!= message.error[i] - if (message.info && message.info.length) .alert.alert-info.alert-dismissable button.close(type="button", data-dismiss="alert", aria-hidden="true") &times; - for (i = 0; i < message.info.length; i++) .center!= message.info[i] - message.info = message.error = [] // REMEMBER to reset messages to an empty array 
+2
source

There was a similar solution, the solution looked like:

 req.flash('error', 'validation failed'); res.redirect('back'); 

Using the back seems to support a flash message, where it redirects to the same route loses.

+1
source

If you are using Express 3, the built-in flash function has been removed. To get the same functionality, you will want to install the connect-flash module, and then add the code from this Gist immediately after initializing your sessions and before app.use(app.router); : https://gist.github.com/3070950

0
source

All Articles