Reputation: 2923
I am a newbie in NodeJS. I have a problem that I am unable to show flash message in my view. Here is my Controller,
index : function(req, res){
res.locals.flash = _.clone(req.session.flash);
res.locals.layout = false;
res.view('login');
},
login : function(req, res){
....
if(!admin){
req.session.flash = {
err : 'User is not found.' // My flash message
}
res.locals.layout = false;
res.redirect('login');
return;
}
.....
}
Here is my view,
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
<% JSON.stringify(flash.err) %>
</div>
<% } %>
When login is false, it show only an empty alert box. And I have a second problem. When I refresh page, The alert box isn't disappeared.
Could someone help me please. Thanks a lot.
Upvotes: 1
Views: 2450
Reputation:
The alert box keeps on appearing because the req.session.flash
object persists the session, so you need to null that out once it's used, or you can just simply use req.flash()
, which does that for you. So change your index
method to something like this:
index: function(req, res) {
// req.flash() returns the contents of req.session.flash and flushes it
// so it doesn't appear on next page load. No need to clone.
res.locals.flash = req.flash();
res.locals.layout = false;
res.view('login');
},
Now, onto the second problem. The error messages aren't appearing because you aren't using the proper EJS
syntax to output escaped values into the view. All you need to do is change your code to this:
<% if(flash && flash.err) { %>
<div class="alert alert-danger">
// Change <% to <%=
<%= flash.err %>
</div>
<% } %>
No need to JSON.stringify, unless you like the quotes. Notice that I changed the <%
to <%=
, which in EJS means "escape this and output it". It's not template HTML or anything like that, so it's okay to escape it anyway.
Upvotes: 4