NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
Flash message in expressjs
express-flash
Flash is an extension of connect-flash. Connect-flash is a module for Node.js. it is used to show flash message whenever action is done.
npm install express express-session connect-flash --save
express is required by the connect-flash library to run. We are using express-session so that a session can be created whenever a message is flashed and the user is redirected to the specified page.
flash messages that work with rendering or redirecting.
var flash = require('express-flash');
########################### OR ###############
const flash = require('connect-flash');
Example
File Name :
const express = require('express');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
const port = process.env.PORT || 3000;
app.use(session({
secret:'mahi',
saveUninitialized: true,
resave: true
}));
app.use(flash());
app.get('/', (req, res) => {
req.flash('message', 'Success Message!!');
res.redirect('/afterlogin');
});
app.get('/afterlogin', (req, res) => {
res.send(req.flash('message'));
});
app.listen(port, (err) => {
if (err) console.log(err);
console.log('Server Error', port);
});
In above Example, defining a session-secret is used for our sensitive information is encrypted and SaveUninitialized prevents the browser from using empty sessions. connect-flash module is called by using app.use(flash()).
We are defining a route / , which will first flash(display) the specified message and then redirects the user to /afterlogin route. The /afterlogin will show the specified message on the web-page.
var flash = require('express-flash-messages')
app.use(flash())
app.get('/', function(req, res){
req.flash('notify', 'notification message')
res.render('index')
})
app.get('/redirect', function(req, res){
req.flash('notify', 'successfully redirected to page!')
res.redirect('/')
})
the app.all() method maps to /express-flash. Request baseurl/express-flash to create a message using the req.flash(type, message)
app.all('/express-flash', req, res ) {
req.flash('success', 'My flash message.');
res.redirect(301, '/');
}
Next map the message to the template in the res.render() method of the target route, baseurl/. Here the req.flash(type) getter method returns the message or messages matching the type, success, which are mapped to the template variable, expressFlash.
app.get('/', req, res ) {
res.render('index', {expressFlash: req.flash('success') });
}
File Name :
Finally, display the value of expressFlash, if it exists, in index.ejs.
<p> Express-Flash Demo </p>
<% if ( expressFlash.length > 0 ) { %>
<p>Message: <%= expressFlash %> </p>
<% } %>
File Name :
<% if ( message ) { %>
<div class="flash"><%= message %></div>
<% } %>
File Name :
var message = $( '.message' );
if ( message.length ) {
setTimeout( function() {
message.fadeOut( 'slow' );
}, 5000 );
}
File Name :
req.flash() can be used in two ways.
If you use two arguments
req.flash(type, message);
where type is a type of message and message is actual message (both strings), then it adds message to the queue of type type. Using it with one argument
req.flash(type);
show message on view page
<% if(message.success){ %>
<div class="alert alert-success" role="alert">
<%= message.success %>
</div>
<% } %>
alert Message
<% if(success && success.length) {%>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<%= success %>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<% } %>
<% if(error && error.length) {%>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<%= error %>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<% } %>
app.use((req, res, next) => {
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
});
Here, we are using Express middleware so that both req.flash(‘success’) and req.flash(‘error’) are available everywhere across our application.