Express.js应用程序错误:不呈现Flash消息 [英] Express.js application bug: flash messages are not rendered

查看:89
本文介绍了Express.js应用程序错误:不呈现Flash消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 博客应用程序 (点击指向请参见 GitHub 存储库),其中 Express

I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.

每次CRUD操作后尝试添加Flash消息时遇到麻烦.

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

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

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

消息模板(格式为 https://github.com/visionmedia/express-messages并稍加修改):

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>

缺少什么?

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

Note: the express-validator version I am using is 3.2.1.

推荐答案

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

Flash messages are assynchronous therefore you need to wrap, redirect:

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

像这样.

这篇关于Express.js应用程序错误:不呈现Flash消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆