javascriptnode.jsexpressconnect-flash

req.flash() not working when rest succeed


I had a problem flashing the req.flash('success','Page Edited!'); on the admin/pages while I can easily flash req.flash('danger',"Page slug already exsists") when rerendering the page with the correspoding error. It only happens when I redirect and query to mongoDB.

My code is

router.post('/edit-page/:slug',function(req,res){
  req.checkBody('title','title must have a value.').notEmpty();
  req.checkBody('content','Content must have a value.').notEmpty();
  
  var title = req.body.title;
  var slug = req.body.slug.replace(/\s+/g,'-').toLowerCase();
  if (slug=="")slug= title.replace(/\s+/g,'-').toLowerCase();
  var content = req.body.content;
  var id = req.body.id;

  var errors = req.validationErrors();
  if (errors){
      res.render('admin/edit_page',{
          errors:errors,
          title:title,
          slug:slug,
          content:content,
          id:id
         });
         console.log(errors)
      }else{
     Page.findOne({slug: slug,_id:{'$ne':id}}, (err,page)=>{
      if (page){ 
          req.flash('danger',"Page slug already exsists")
          res.render('admin/edit_page',{
              title:title,
              slug:slug,
              content:content,
              id:id
             });
             console.log(errors)
      }else{
          Page.findById(id, function (err,page){
            if(err){
              console.log(err);
            }else{
              page.title=title;
              page.slug=slug;
              page.content=content;
               page.save(function(err){
                
                
              if(err) return console.log(err);
                console.log('debug');
                
                res.redirect('/admin/pages');
           //this is the code that wont flash to another page
                req.flash('success','Page Edited!');
            });
            }
            
            
          });
      }
     });
  }  
});

Solution

  • The issue is that you redirect the user before setting the flash message in

                    res.redirect('/admin/pages');
               //this is the code that wont flash to another page
                    req.flash('success','Page Edited!');
    

    Reversing those lines should work.

    It's not super clear from the docs, but res.redirect() works just like res.send()/res.end() (and is typically the last thing you do in a request handler).