1

I am not able to use connect-flash package for res.render. My main aim is to display a flash message on rendering of a view.

I am able to make it work with a res.redirect("route") but not with the res.render("view") code. Is it by design ?

My code is shown as below

if(err){
      // Apparently res.render("register") didn't work with flash. But res.redirect("/register") worked.
        req.flash("error", err.message);   // Error occurs when the user is taken, password is empty etc.
        return res.redirect("/register");  // Short circut everything. Else the code below this would run as well and that would throw an error
    }
harry
  • 11
  • 6

2 Answers2

3

This is the correct syntax for using req.flash with res.render:

req.flash('error', yourErrString);
res.render("register.ejs", {
   message: req.flash('error')
});
itsundefined
  • 1,409
  • 2
  • 12
  • 32
  • I was trying to do something similar to this. `app.get("/",function(req,res){ req.flash("error", err.message); res.render("index", { message : req.flash('error') }); }` Guess this is not the way connect-flash is supposed to work – harry May 01 '17 at 11:35
0

This worked for me; In my case, I was okay to refresh the page once again it loaded;

window.onload = function () {
    if (!window.location.hash) {
        window.location = window.location + '#loaded';
        window.location.reload();
    }
}
NandaSagar
  • 11
  • 4
  • if you are using ejs then link a script tag at the start of the page so that it reloads and flash message appears. – NandaSagar Jan 02 '23 at 08:39