Flash Messages are not working express/nodejs/ejs

痴心易碎 提交于 2019-12-24 01:25:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!