0

我在 mongoose 函数中调用 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');
});
4

1 回答 1

1

您将其重定向到 /adminpanel/1 而无需等待 findById (async) 函数的响应。这应该有效:

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');
   }
});
于 2019-02-06T06:21:23.763 回答