I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
Before submitting a
I have applied the solution provided by Saravanakumar T N with a small modification in messages.ejs.
I have: this in the controller:
exports.addPost = (req, res, next) => {
const errors = validationResult(req);
const post = new Post();
if (!errors.isEmpty()) {
req.flash('danger', errors.array());
req.session.save(() => res.redirect('../addpost'));
} else {
post.title = req.body.title;
post.short_description = req.body.excerpt
post.full_text = req.body.body;
post.save(function(err) {
if (err) {
console.log(err);
return;
} else {
req.flash('success', "The post was successfully added");
req.session.save(() => res.redirect('/dashboard'));
}
});
}
}
In the view:
<% Object.keys(messages).forEach(function (type) { %>
<% messages[type].forEach(function (message) { %>
<% if (type === 'danger') { %>
<%= message.msg %>
<%} else { %>
<%= message %>
<% } %>
<% }) %>
<% }) %>