To display flash messages using the connect-flash
module in Node.js and Express, you will need to perform the following steps:
- Install the
connect-flash
module by runningnpm install connect-flash
in your terminal.
2. In your Express app, require the connect-flash
module and add it as middleware. For example:
1 2 3 |
const flash = require('connect-flash'); app.use(flash()); |
- In your route handlers, set flash messages using the
req.flash
function. For example:
1 |
req.flash('success', 'Welcome to our website!'); |
- In your views, display the flash messages using the
req.flash
function. For example, in an EJS template:
1 2 3 4 5 |
<% if (success) { %> <div class="alert alert-success"> <%= success %> </div> <% } %> |
- Make sure to call
req.flash()
after each redirect, otherwise the message will be lost.
6) You can also add different type of flash message like error, success, warning and info.