问题
I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
I run into trouble while trying to add flash messages after every CRUD operation.
For Add Post (the operation itself works), I have:
exports.addPost = (req, res, next) => {
const post = new Post();
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 {
// Confirmation message
req.flash('success', "Post added");
res.redirect('/dashboard');
}
});
}
In my index.js file I have added all the necessary packages and middleware:
const expressValidator = require("express-validator");
const flash = require("connect-flash");
const session = require("express-session");
// more code
// Express Sessions Middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
// Express Messages Middleware
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Express Validator Middleware
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
The messages template (taken form https://github.com/visionmedia/express-messages and slightly modified):
<div id="messages">
<% Object.keys(messages).forEach(function (type) { %>
<% messages[type].forEach(function (message) { %>
<div class="alert alert-<%= type %>"><%= message %></div>
<% }) %>
<% }) %>
</div>
I thought I did everything right and yet the messages container is rendered empty:
<div id="messages">
// messages should be here
</div>
What is missing?
Note: the express-validator
version I am using is 3.2.1
.
回答1:
Flash messages are assynchronous therefore you need to wrap, redirect:
req.flash('success', "Post added");
req.session.save(() => res.redirect('/dashboard'));
Like so.
来源:https://stackoverflow.com/questions/60523876/express-js-application-bug-flash-messages-are-not-rendered