How can we flash messages in node.js from inside promises? I used the library 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
req
==! res
:)
I hope it helps you!
connect-flash
is just a kind of store for messages. 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):
p= messages
It is worth mentioning that flash()
returns an array of messages, even when you flash only once . 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. 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
):
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 });
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.