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.