0

I'm hoping someone can help with showing flash messages in Express via a Handlebars view (which uses the bootstrap markup).

In app.js I have the below modules and middleware to try and get flashes working

//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;

and a route router.post('/store/add', storeController.createStore);

which has the controller function

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

when I create a new store and am redirected to homepage the console.log shows the correct value my-messages { error: [ 'leave a review' ] } but I cannot get it into the view

my homepage ('/') view is

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

but nothing shows up. I've read quite a few similar questions on SO, but can't seem to get this right.

Any help much appreciated.

4

1 回答 1

1

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

在我添加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) 中,我在要点中添加了示例:

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(它使用contains来自 npmjs.com/package/handlebars-helpers 的助手:

{{#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}}中。这给了我带有引导样式的闪存消息。

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

于 2018-01-28T10:54:52.293 回答