Express+Handlebars实现Bootstrap风格Flash消息显示问题求助
Hey there, let's work through why your flash messages aren't showing up in your Handlebars view—you're really close, just a couple of key tweaks needed!
1. You're accidentally clearing your flash messages in the controller
Look at this line in your createStore function:
req.flash('error', 'leave a review'); console.log('my-messages',req.flash()); // This is the problem!
When you call req.flash() with no arguments, it fetches AND clears all flash messages in one go. By the time your redirect completes and the homepage renders, the message is already gone.
Fix this by either:
- Storing the messages first before logging them (so you don't empty the store):
req.flash('error', 'leave a review'); const flashMessages = req.flash(); console.log('my-messages', flashMessages); // Wait, no—this still clears them! Instead, check the session directly for debugging: console.log('my-messages', req.session.flash); res.redirect('/'); - Or just removing the debug log entirely while testing the flash functionality.
2. Your Handlebars view is using the wrong variable names
In your app.js, you're attaching flash messages to res.locals.flashes:
res.locals.flashes = req.flash();
But your view is checking for {{message}} or {{errors}}—these don't match the variable you've set up. Plus, connect-flash stores messages of each type in an array (so you can have multiple error messages at once).
Update your homepage view to target the error flash type correctly:
<h1>{{title}}</h1> <p>Hi! Welcome to {{title}} </p> <p>This page was built by {{created}}</p> {{!-- Render error flash messages --}} {{#if flashes.error}} {{#each flashes.error}} <div class="alert alert-danger">{{this}}</div> {{/each}} {{/if}}
Quick sanity check: Middleware order
Your middleware sequence in app.js looks correct:session → flash → custom middleware that attaches flashes to res.locals
This is important because connect-flash relies on session data, and your custom middleware needs to run after flash to access the messages.
Once you fix those two main issues, your flash message should render properly in the Bootstrap alert on your homepage.
内容的提问来源于stack exchange,提问作者Stuart Brown

