You are calling flash method in middleware and this is the expected behaviour of middleware. Middleware will read the message on next request & set it local variables according to your logic.
How middle ware works?
When a request comes in, it is passed off to the first middleware function, along with a wrapped ServerResponse object and a next callback. Middle ware can decide to respond by calling methods on the response object, and/or pass the request off to the next layer in the stack by calling method next()
.
connect-flash
The flash is a special area of the session used for storing messages. Messages are written to the flash and cleared after being displayed to the user. The flash is typically used in combination with redirects, ensuring that the message is available to the next page that is to be rendered.
I am getting the message only after refresh/redirect?
app.use(function(req, res, next) {
res.locals.messages = req.flash();
next();
});
Above middleware will call on every request & set the req.flash()
value. Because of this you will get the req.flash('success', {msg: 'Sign Up Success'});
values on every next(subsequent) request. Not on the current page without redirecting/refreshing the page.
To override this behaviour to get the values without refresh you have call the req.flash()
function that can be used for flash messages in your router with res.locals.messages = req.flash();
.
Ex:- To Show failed login message on the page without page refresh and on success redirect page after setting new flash message in router.
router.post("/login", function (req, res) {
var username = req.body.username;
var pwd = req.body.pwd;
if (username === "demo" && pwd === "demo") {
req.flash("messages", { "success" : "Sign Up Success" });
res.redirect("/me/dashboard");
} else {
req.flash("messages", { "error" : "Invalid username or password" });
res.locals.messages = req.flash();
res.render("login", { title: "Login"});
}
});
Conclusion: To get the messages on the same page. Override the behaviour of middleware by assigning values in the router itself.
req.flash('success', {msg: 'Sign Up Success'}); res.redirect('/me/dashboard');
– Lenity