我在猫鼬函数内调用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');
});
答案 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');
}
});