Node.js 如何从mongoose内部调用req.flash()?
在mongoose函数中调用req.flash时出现问题。我什么都试过了。在我的代码中,有一部分是有效的,但在另一部分是无效的 我的代码:Node.js 如何从mongoose内部调用req.flash()?,node.js,express,mongoose,connect-flash,Node.js,Express,Mongoose,Connect Flash,在mongoose函数中调用req.flash时出现问题。我什么都试过了。在我的代码中,有一部分是有效的,但在另一部分是无效的 我的代码: router.post('/chngpwd', function(req, res, next) { var {currentpassword, newpassword, confirmnewpassword} = req.body; var uid = req.session.passport.user; if (newpassword
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');
});
您正在将其重定向到/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');
}
});
您是否收到任何错误消息?预期的行为是什么?发生了什么?我没有收到任何错误,也没有任何变化。即使我控制台日志req.session,flash中也没有存储任何内容。谢谢,现在它可以工作了。我只是想知道我是否可以一次重定向所有flash消息。可能吗?@kogik也许您可以使用async/await语法来等待User.findByIduid调用完成。@GCSDC非常感谢您。现在使用async可以更好地工作。