NodeJS Express App - 通过Handlebars显示Flash消息

时间:2018-01-27 21:30:33

标签: node.js express handlebars.js express-handlebars connect-flash

我希望有人可以通过Handlebars视图(使用bootstrap标记)帮助在Express中显示flash消息。

在app.js中我有以下模块和中间件试图让闪烁工作

//require modules
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const hbs = require('express-handlebars');
const session = require('express-session');
const flash = require('connect-flash');
const routes = require('./routes/index');
const app = express();

// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout',layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(expressValidator());

app.use(cookieParser());

app.use(session({
secret: process.env.SECRET,
key: process.env.KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

app.use(flash());

app.use((req, res, next) => {
res.locals.h = helpers;
res.locals.flashes = req.flash();
res.locals.user = req.user || null;
res.locals.currentPath = req.path;
next();
});

app.use('/', routes);

module.exports = app;

和一条路线 router.post('/store/add', storeController.createStore);

具有控制器功能

exports.createStore = async (req, res) => {
  const store = new Store(req.body);
  await store.save();
  req.flash('error', 'leave a review');
  console.log('my-messages',req.flash());
  res.redirect('/');    
};

当我创建一个新商店并重定向到主页时,console.log会显示正确的值my-messages { error: [ 'leave a review' ] },但我无法将其置于视图中

我的主页('/')视图是

<h1>{{title}}</h1>
  <p>Hi! Welcome to {{title}} </p>
  <p>This page was built by {{created}}</p>

 {{#if message}}
<div class="alert alert-danger">{{message}}</div>
{{/if}}

{{#if errors}}
    {{#each errors}}
        <div class="error">
            {{msg}}
        </div>
    {{/each}}
{{/if}}

但没有出现。我已经在SO上阅读了不少类似的问题,但似乎无法做到这一点。

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:0)

好的,这就是我根据此https://gist.github.com/brianmacarthur/a4e3e0093d368aa8e423答案基于https://stackoverflow.com/a/28221732/1699434工作的方式。

app.use(flash()) app.js之后,我添加了:

app.use(function(req, res, next){
// if there's a flash message in the session request, make it available 
in the response, then delete it
  res.locals.sessionFlash = req.session.sessionFlash;
  delete req.session.sessionFlash;
  next();
});

在我的路线文件(index.js)中,我在gist中添加了示例:

router.all('/session-flash', function( req, res ) {
  req.session.sessionFlash = {
    type: 'info',
    message: 'This is a flash message using custom middleware and express-session.'
  }
  res.redirect(301, '/');
});

然后我创建了一个部分message.hbs的把手(使用来自npmjs.com/package/handlebars-helpers的contains助手:

{{#if sessionFlash.message}}
  <div id="flash-messages" class="container">
      {{#contains sessionFlash.type "info"}}
      <div class="alert alert-info">
            {{{sessionFlash.message}}}
      </div>
      {{/contains}}
      {{#contains sessionFlash.type "success"}}
      <div class="alert alert-success">
              {{{sessionFlash.message}}}
      </div>
      {{/contains}}
      {{#contains sessionFlash.type "warning"}}
      <div class="alert alert-warning">
            {{{sessionFlash.message}}}
      </div>
       {{/contains}}
      {{#contains sessionFlash.type "error"}}
      <div class="alert alert-danger">
            {{{sessionFlash.message}}}
      </div>
      {{/contains}}
  </div>
{{/if}}

然后我可以将其包含在我的其他手柄模板{{> message}}中。这给了我带有引导样式的flash消息。

不幸的是,我无法同时发送多个闪存(相同或不同类型),但我认为这在https://gist.github.com/brianmacarthur/a4e3e0093d368aa8e423中作为中间件方法的限制进行了讨论。随着我了解更多,也许我会解决这个问题,但我现在还没有多个flash消息的用例:)