javascriptnode.jsmongodbexpressconnect-flash

Express connect-flash displays only after refresh not on the same page.how to solve this?


below is register route

 router.post("/register", function(req, res){
var newUser=    new User({username:req.body.username});
   User.register(newUser,req.body.password, function(error,user){
       if(error){
          req.flash("error", error.message);
            return res.render("register.ejs");
       }else{
           passport.authenticate("local")(req, res ,function(){
                req.flash("success","Welcome to PhotoDiary, " + user.username);
               res.redirect("/diary");
           });
       }
   });
});

below is passport-local

app.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();

i put flash-connect in register route req.flash("error", error.message); when i sign up it shows the message after another refresh,not on the same page


Solution

  • Its not a good practice to use res.locals for sending errors to views, Assuming You are using EJS or Pug you can also send your messages and other data to view file in this way.

    router.post("/register", function(req, res){
    var newUser=    new User({username:req.body.username});
    User.register(newUser,req.body.password, function(error,user){
           if(error){
               req.flash("error", "An Error Has Occured");
               var data = {
                  page_title : 'Register', // Set Page Title Dynamically
                  message : req.flash('error'), // Set Message
               };
                return res.render("register.ejs" , data);
           }else{
               passport.authenticate("local")(req, res ,function(){
               req.flash("success","Welcome to PhotoDiary");
               var data = {
                  page_title : 'Register', // Set Page Title Dynamically
                  username : user.username,
                  message : req.flash('success'), // Set Message
               };
                  res.redirect("/diary", data);
               });
           }
       });
    });

    You will have access to the data in your view file using the variables in this way (Example for EJS)

    <Head>
       <title><%= page_title %></title>
    </head>
    
    <div class="alert alert-success">
          <%= message %> <%= username %> 
    </div>
    
    <h1> Welcome </h1>