As an asynchronous event driven JavaScript runtime, Node is designed to build scalable network applications. And its popularity in the web development is increasing day by day, for its fastest server response and other functionality. My topic is to show a flash message on the client side using node and express js.
You have to know that flash messages are messages that are stored on the server for the duration between two requests from the same client, and thus are only available in the next request. So it will use for one time purpose. Now follow my step to use flash message in your project.
Step 1:
We have to install some modules to use flash. Let’s go to your project folder and open cmd on that directory. Then start download all the specific modules one by one by using cmd.
npm install express-session --save npm install cookie-parser --save npm install connect-flash --save
Step 2:
Now we have to add some code into the app.js file to access those module. Let’s add these code.
var session = require('express-session'); var cookieParser = require('cookie-parser'); var flash = require('connect-flash'); var app = express(); app.use(cookieParser('secret')); app.use(session({cookie: { maxAge: 60000 }})); app.use(flash());
Step 3:
Now I will use flash message after a registration using form-submit. Means when a user register himself in my site then he/she will get a flash message after completing registration. I will just show you the submit function in app.js.
app.post('/registration',function(req, res){ var uname = req.body.username; var email = req.body.email; var password = req.body.password; var sql = "INSERT INTO registration (name, email, password) values('"+uname+"','"+email+"','"+password+"')"; con.query(sql, function(err, rows){ if(err){ throw err; } else{ req.flash('success', 'Registration successfully'); res.locals.message = req.flash(); res.render('index'); } }); });
Step 4:
Now we just use this in the views file. In my case I will use it in the index.ejs file. And I have attached it like I have done in the bellow.
<% if(locals.message){ %> <div class="alert alert-success" role="alert"> <strong>Well done!</strong> <%=message.success%> </div> <% } %>
Now run the code and if everything is alright then it will work. If any question regarding this post then please put it in the comment section.
I just spent 3 hours trying to get flash messaging to work and when I have just about had it with this package it worked after adding express flash 2. This is not the first time this package has driven me nuts, it has to be the most temperamental
express package known to man. If anyone can give me an explanation as to why it is so difficult, please let me know!
Kind Regards Ajax27
After spending lots of time, finally, this worked for me. Thank you for the knowledge