How do I display flash message without page refresh using express and connect-flash?
Asked Answered
L

1

15

Express connect-flash displays only after refresh. Code is stripped for easy reading.

"express": "~4.2.0",
"connect-flash": "~0.1.1",

And here is my app.js

var express = require('express'),
    favicon = require('serve-favicon'),
    flash = require('connect-flash');
var app = express();
app.use(cookieParser('---'));
app.use(session({
  secret: '---',
  saveUninitialized: true,
  resave: true}));
app.use(flash());

app.use(function(req, res, next) {
  res.locals.messages = req.flash();
  next();
});

In my route i tried something like

req.flash('success', {msg: 'Sign Up Success'});
res.redirect('/me/dashboard');

and my error display msg.jade template is

for msg in messages
      div #{msg.msg}

I am getting the message only after refresh/redirtect. Please let me know what i am doing wrong.

I seen this as well but its outdated i think

Lenity answered 25/8, 2014 at 7:7 Comment(7)
Have you debugged the res.locals.messages = req.flash(); line? Note that req.flash() returns a object, not an arrayDishonest
when do you expect to get the message, flash is supposed to be available to the next page that is to be rendered. If you need an immediate flash of notification after a post or something, you need to do it on the front end.Gilolo
In the second code snippet I am setting flash message and redirecting to another page. Does that work ?Lenity
@muzk i think that's not the problem since I am getting the message in next refresh. Am I missing something ?Lenity
@rajeshujade In my route i tried something like req.flash('success', {msg: 'Sign Up Success'}); res.redirect('/me/dashboard'); Lenity
@NikhilM According to your app.js you are trying to access it global.I wants to know how do you pass the flash message to views using router like ` res.render('login', { title: 'Express',messages: req.flash('messages')});`or are you trying to access it as a global variable. If you post that snippet it will helpful.Chinese
@rajeshujade i am trying to access the global variable not sending explicitly with each request.Lenity
C
19

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.

Chinese answered 18/9, 2014 at 9:57 Comment(1)
This way still not working.Problem

© 2022 - 2024 — McMap. All rights reserved.