【问题标题】:Express.js application bug: flash messages are not renderedExpress.js 应用程序错误:Flash 消息未呈现
【发布时间】:2020-06-16 19:36:15
【问题描述】:

我正在使用ExpressEJS 和 MongoDB 开发 blogging application(单击链接查看 GitHub 存储库)。

我在每次 CRUD 操作后尝试添加 flash 消息时遇到了麻烦。

对于添加帖子(操作本身有效),我有:

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');
        }
    });
}

在我的 index.js 文件中,我添加了所有必要的包和中间件:

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
    };
  }
}));

消息模板(采用https://github.com/visionmedia/express-messages 并稍作修改):

<div id="messages">
  <% Object.keys(messages).forEach(function (type) { %>
        <% messages[type].forEach(function (message) { %>
            <div class="alert alert-<%= type %>"><%= message %></div>
        <% }) %>
  <% }) %>
</div>

我以为我做的一切都是正确的,但消息容器却是空的:

<div id="messages">
 // messages should be here
</div>

缺少什么?

注意:我使用的express-validator版本是3.2.1

【问题讨论】:

    标签: node.js express flash


    【解决方案1】:

    Flash 消息是异步的,因此您需要包装、重定向:

    req.flash('success', "Post added");
    req.session.save(() => res.redirect('/dashboard'));
    

    像这样。

    【讨论】:

    • 编辑了答案。对不起,我在手机上,它变得很有挑战性?
    • 不使用es6语法试试
    • 请帮我处理一下 this question。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    相关资源
    最近更新 更多