flash messages are not saved before the page is rendered (node)












0















As part of a generic get route in an express application, I want to send two flash messages with express-session and connect-flash. This all works except that req.flash does not save before the page is rendered. As a result, the flash messages do not show until the user loads another page or the same page again.



The code for the last function in the route:



    Post.countDocuments().exec(function(err, count){
if(err) {
console.log(err);
res.redirect("back");
}

req.flash("success", ["It's working", "Hallelujah!"]);
req.flash("error", ["Uh oh!", "We have a problem..."]);

res.render("index", {posts: allPosts, dates: dates, current: pageNumber, pages: Math.ceil(count / pageLimit), showing: showing, total: count});
});


and here's the code for one of the flash message templates (ejs):



    <div class="flash flash-success">
<div class="flash-header">
<span class="flash-title flash-title-success"><i class="fas fa-check"></i> <%= success[0] %></span>
<span class="flash-close" onclick="return closeFlash(this);"><i class="fas fa-times"></i></span>
</div>

<hr class="flash-hr">
<div class="flash-body-success"><%= success[1] %></div>
</div>


I have tried using .exec() after req.flash to make the render statement run on completion but this didn't work and I've also tried req.session.save() with the render statement in a callback but this also failed.



The issue is not resolved by getting rid of one of the req.flash statements nor by only passing one string argument instead of an array of two.










share|improve this question



























    0















    As part of a generic get route in an express application, I want to send two flash messages with express-session and connect-flash. This all works except that req.flash does not save before the page is rendered. As a result, the flash messages do not show until the user loads another page or the same page again.



    The code for the last function in the route:



        Post.countDocuments().exec(function(err, count){
    if(err) {
    console.log(err);
    res.redirect("back");
    }

    req.flash("success", ["It's working", "Hallelujah!"]);
    req.flash("error", ["Uh oh!", "We have a problem..."]);

    res.render("index", {posts: allPosts, dates: dates, current: pageNumber, pages: Math.ceil(count / pageLimit), showing: showing, total: count});
    });


    and here's the code for one of the flash message templates (ejs):



        <div class="flash flash-success">
    <div class="flash-header">
    <span class="flash-title flash-title-success"><i class="fas fa-check"></i> <%= success[0] %></span>
    <span class="flash-close" onclick="return closeFlash(this);"><i class="fas fa-times"></i></span>
    </div>

    <hr class="flash-hr">
    <div class="flash-body-success"><%= success[1] %></div>
    </div>


    I have tried using .exec() after req.flash to make the render statement run on completion but this didn't work and I've also tried req.session.save() with the render statement in a callback but this also failed.



    The issue is not resolved by getting rid of one of the req.flash statements nor by only passing one string argument instead of an array of two.










    share|improve this question

























      0












      0








      0








      As part of a generic get route in an express application, I want to send two flash messages with express-session and connect-flash. This all works except that req.flash does not save before the page is rendered. As a result, the flash messages do not show until the user loads another page or the same page again.



      The code for the last function in the route:



          Post.countDocuments().exec(function(err, count){
      if(err) {
      console.log(err);
      res.redirect("back");
      }

      req.flash("success", ["It's working", "Hallelujah!"]);
      req.flash("error", ["Uh oh!", "We have a problem..."]);

      res.render("index", {posts: allPosts, dates: dates, current: pageNumber, pages: Math.ceil(count / pageLimit), showing: showing, total: count});
      });


      and here's the code for one of the flash message templates (ejs):



          <div class="flash flash-success">
      <div class="flash-header">
      <span class="flash-title flash-title-success"><i class="fas fa-check"></i> <%= success[0] %></span>
      <span class="flash-close" onclick="return closeFlash(this);"><i class="fas fa-times"></i></span>
      </div>

      <hr class="flash-hr">
      <div class="flash-body-success"><%= success[1] %></div>
      </div>


      I have tried using .exec() after req.flash to make the render statement run on completion but this didn't work and I've also tried req.session.save() with the render statement in a callback but this also failed.



      The issue is not resolved by getting rid of one of the req.flash statements nor by only passing one string argument instead of an array of two.










      share|improve this question














      As part of a generic get route in an express application, I want to send two flash messages with express-session and connect-flash. This all works except that req.flash does not save before the page is rendered. As a result, the flash messages do not show until the user loads another page or the same page again.



      The code for the last function in the route:



          Post.countDocuments().exec(function(err, count){
      if(err) {
      console.log(err);
      res.redirect("back");
      }

      req.flash("success", ["It's working", "Hallelujah!"]);
      req.flash("error", ["Uh oh!", "We have a problem..."]);

      res.render("index", {posts: allPosts, dates: dates, current: pageNumber, pages: Math.ceil(count / pageLimit), showing: showing, total: count});
      });


      and here's the code for one of the flash message templates (ejs):



          <div class="flash flash-success">
      <div class="flash-header">
      <span class="flash-title flash-title-success"><i class="fas fa-check"></i> <%= success[0] %></span>
      <span class="flash-close" onclick="return closeFlash(this);"><i class="fas fa-times"></i></span>
      </div>

      <hr class="flash-hr">
      <div class="flash-body-success"><%= success[1] %></div>
      </div>


      I have tried using .exec() after req.flash to make the render statement run on completion but this didn't work and I've also tried req.session.save() with the render statement in a callback but this also failed.



      The issue is not resolved by getting rid of one of the req.flash statements nor by only passing one string argument instead of an array of two.







      node.js express connect-flash






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 20:57









      Adam BAdam B

      808




      808
























          1 Answer
          1






          active

          oldest

          votes


















          0














          The problem was that I had



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


          in app.js and so this middleware was run before the route had chance to set values for req.flash meaning that error and success were set to be empty.



          I solved this by creating a function to save req.flash in res.locals just before rendering the page:



          var toolsObj = {};

          toolsObj.saveFlash = function(req, res) {
          res.locals.error = req.flash("error");
          res.locals.success = req.flash("success");
          };

          module.exports = toolsObj;





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53462297%2fflash-messages-are-not-saved-before-the-page-is-rendered-node%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            The problem was that I had



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


            in app.js and so this middleware was run before the route had chance to set values for req.flash meaning that error and success were set to be empty.



            I solved this by creating a function to save req.flash in res.locals just before rendering the page:



            var toolsObj = {};

            toolsObj.saveFlash = function(req, res) {
            res.locals.error = req.flash("error");
            res.locals.success = req.flash("success");
            };

            module.exports = toolsObj;





            share|improve this answer




























              0














              The problem was that I had



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


              in app.js and so this middleware was run before the route had chance to set values for req.flash meaning that error and success were set to be empty.



              I solved this by creating a function to save req.flash in res.locals just before rendering the page:



              var toolsObj = {};

              toolsObj.saveFlash = function(req, res) {
              res.locals.error = req.flash("error");
              res.locals.success = req.flash("success");
              };

              module.exports = toolsObj;





              share|improve this answer


























                0












                0








                0







                The problem was that I had



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


                in app.js and so this middleware was run before the route had chance to set values for req.flash meaning that error and success were set to be empty.



                I solved this by creating a function to save req.flash in res.locals just before rendering the page:



                var toolsObj = {};

                toolsObj.saveFlash = function(req, res) {
                res.locals.error = req.flash("error");
                res.locals.success = req.flash("success");
                };

                module.exports = toolsObj;





                share|improve this answer













                The problem was that I had



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


                in app.js and so this middleware was run before the route had chance to set values for req.flash meaning that error and success were set to be empty.



                I solved this by creating a function to save req.flash in res.locals just before rendering the page:



                var toolsObj = {};

                toolsObj.saveFlash = function(req, res) {
                res.locals.error = req.flash("error");
                res.locals.success = req.flash("success");
                };

                module.exports = toolsObj;






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 25 '18 at 12:08









                Adam BAdam B

                808




                808
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53462297%2fflash-messages-are-not-saved-before-the-page-is-rendered-node%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Create new schema in PostgreSQL using DBeaver

                    Deepest pit of an array with Javascript: test on Codility

                    Fotorealismo