1

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

1 回答 1

0

问题是您在设置闪存消息之前重定向用户

                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()(通常是您在请求处理程序中做的最后一件事)。

于 2020-10-29T19:12:55.380 回答