问题
Flash messages seem to not be working and I think I am missing something super obvious, but I've been at it an hour, and I still have no idea on why it is not working.
My Middleware:
// Session middleware
app.use(session({
secret: 'stuffedbagels',
resave: true,
saveUninitialized: true
}));
// Express Messages middleware
app.use(require('connect-flash')());
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
App route, just for testing purposes.
// Route that creates a flash message using the express-flash module
app.all('/express-flash', function( req, res ) {
req.flash('success', 'This is a flash message using the express-flash module.');
res.redirect(301, '/');
});
Template (copied right from their github)
<div id="messages">
<% Object.keys(messages).forEach(function (type) { %>
<ul class="<%= type %>">
<% messages[type].forEach(function (message) { %>
<li><%= message %></li>
<% }) %>
</ul>
<% }) %>
</div>
How I'm rendering it
<%- messages('msg_temp', locals) %>
Now I'm not sure what's wrong, and I've tried every possible fix I found on here, and through google, but it just doesn't seem to to want to work.
回答1:
you need to set message with a key like error/success
req.flash('success', "hello flash");
and you'll get same key in your res.locals or can say while rendering on view like
{% if success %}
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
{{ success }}
</div>
{% endif %}
NOTE: flash store key in session cookie, message flushed only once
来源:https://stackoverflow.com/questions/47785543/flash-messages-are-not-working-express-nodejs-ejs