req.flash() 休息成功时不工作

req.flash() not working when rest succeed

我在 admin/pages 上闪烁 req.flash('success','Page Edited!'); 时遇到问题,而在使用相应错误重新呈现页面时我可以轻松地闪烁 req.flash('danger',"Page slug already exsists")。只有当我重定向并查询到 mongoDB.

时才会发生

我的密码是

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!');
            });
            }
            
            
          });
      }
     });
  }  
});

问题是您在

中设置即显消息之前重定向了用户
                res.redirect('/admin/pages');
           //this is the code that wont flash to another page
                req.flash('success','Page Edited!');

反转这些行应该可以。

从文档中看不是很清楚,但是 res.redirect() 的工作方式与 res.send()/res.end() 一样(通常是您在请求处理程序中做的最后一件事)。