如何从猫鼬内部调用req.flash()?

时间:2019-02-05 18:51:15

标签: node.js express mongoose connect-flash

我在猫鼬函数内调用req.flash时遇到问题。我试过了一切。在我的代码的一部分中,它可以工作,而在其他部分中,则不能。

我的代码:

 router.post('/chngpwd', function(req, res, next) {
   var {currentpassword, newpassword, confirmnewpassword} = req.body;
   var uid = req.session.passport.user;
   if (newpassword == confirmnewpassword) {
     User.findById(uid).then(dbres => {
     req.flash('error_msg',"THIS MESSAGE DON'T WORK");  //DONT WORK
     });
   }else {
     req.flash('error_msg',"New passwords don't match"); //WORKS
   }
   res.redirect('/adminpanel/1');
});

1 个答案:

答案 0 :(得分:1)

您将其重定向到/ adminpanel / 1,而无需等待findById(异步)函数的响应。 这应该起作用:

router.post('/chngpwd', function(req, res, next) {
   var {currentpassword, newpassword, confirmnewpassword} = req.body;
   var uid = req.session.passport.user;
   if (newpassword == confirmnewpassword) {
     User.findById(uid).then(dbres => {
         req.flash('error_msg',"THIS MESSAGE DON'T WORK");
         res.redirect('/adminpanel/1');
     });
   }else {
     req.flash('error_msg',"New passwords don't match");
     res.redirect('/adminpanel/1');
   }
});