[英]How to flash messages from inside promises in node.js?
How can we flash messages in node.js from inside promises?我们如何从 Promise 内部在 node.js 中闪现消息? I used the library connect-flash https://github.com/jaredhanson/connect-flash .
我使用了库 connect-flash https://github.com/jaredhanson/connect-flash 。
The following code doesn't work:以下代码不起作用:
Patient.findOne({
hospitalNumber
}).then((patient) => {
if (_.isEmpty(patient)) {
throw Error('Patient does not exist');
}
res.status(200).render('patientPage');
}).catch((err) => {
console.log(err);
req.flash('error_msg', "Something went wrong.");
res.redirect(400, '/app');
});
well, according to the library docs:好吧,根据图书馆文档:
req.flash('blah')
your code has res.flash
你的代码有
res.flash
req
==! req
==! res
:) :)
I hope it helps you!我希望它能帮助你!
connect-flash
is just a kind of store for messages. connect-flash
只是一种消息存储。 You still need to provide them to the render and render them yourself.您仍然需要将它们提供给渲染器并自己渲染它们。
So add them to the render call...所以将它们添加到渲染调用中...
res.redirect(400/*?*/, '/app', { messages: req.flash('error_msg') });
...and place them on your template (here assuming you use pug): ...并将它们放在您的模板上(这里假设您使用 pug):
p= messages
It is worth mentioning that flash()
returns an array of messages, even when you flash only once .值得一提的是,
flash()
返回一组消息,即使您只闪烁一次。 So, to have better control you may use something like:因此,为了更好地控制,您可以使用以下内容:
each message in messages
p= message
Finally there is no special handling of flashes within promises.最后,promise 中没有对 flash 的特殊处理。 Everything you flash will be available to the renderer.
您闪烁的所有内容都可用于渲染器。 So you could change your code to:
因此,您可以将代码更改为:
Patient.findOne({
hospitalNumber
}).then((patient) => {
if (_.isEmpty(patient)) {
req.flash('error', 'Patient does not exist');
throw Error('Patient does not exist');
}
res.status(200).render('patientPage');
}).catch((err) => {
console.log(err);
res.redirect(400, '/app', { errors: req.flash('error') });
});
or, better yet (but without flash, note error
instead of errors
):或者,更好(但没有闪存,请注意
error
而不是errors
):
Patient.findOne({
hospitalNumber
}).then((patient) => {
if (_.isEmpty(patient)) {
throw Error('Patient does not exist');
}
res.status(200).render('patientPage');
}).catch((err) => {
console.log(err);
res.redirect(400, '/app', { error: err.message });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.