'req.flash not showing message
I'm using Handlebars in my express project. and I use req.flash() method but it won't Show up in my hbs file.
Here's my Code :
req.flash('message','Tag already exists');
res.redirect('/p/tags/add');
In .hbs file :
{{#if message}}
<h1>Tag Already ِExists</h1>
{{/if}}
Also in my app.js :
app.use(flash());
What Seems to be the problem?
Thanks in advance!
Solution 1:[1]
You need to use your flash message inside your redirected URL like this:
app.get('/p/tags/add', function(req, res){
res.render('yourhbsfile', { message: req.flash('message') });
});
EDIT: So to clarify about the confusion on flash message, it can be set from anywhere before redirecting to any route or inside any middleware before using res.render() and can propagate that message inside req or request object. you may print req and check flash object for better understanding.
Solution 2:[2]
It's true you can't add flash with redirection.
You have to execute flash function before redirection and then you have to use it inside the render function.
boo = (req, res) => {
req.flash("error", "This is an error!");
return res.redirect("/index");
}
- Im using Routes, when viewing the /index page the
indexPagefunction is executed.
Render function to view /index page.
indexPage = (req, res) => {
let message = req.flash();
res.render("index", {
message: message,
});
}
And how to view the data in Handlebar index.hbs
{{#if message.error}}
{{{message.error}}}
{{/if}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sindri Þór |
