Some time we need to print a message after the redirection of page.
Like when you delete a post and will show “Post deleted successfully!” after reloading or redirecting the page.
I’m going to explain how we can redirect to another page in node js along with message.
First you need to install express-session using below command if you have not installed:
1
|
sudo npm install express-session --save
|
Now you need to install req-flash using below command. It flash the message but this library is dependent on session.
1
|
sudo npm install req-flash --save
|
Now in app.js include following:
1
2
|
var session = require('express-session');
var flash = require('req-flash');
|
If you are using express js might be you don’t need to put this line because this is already there.
1
|
app.use(cookieParser());
|
Now you need to use session if you have not used it in app.js yet:
1
2
3
4
5
|
app.use(session({
secret: 'djhxcvxfgshajfgjhgsjhfgsakjeauytsdfy',
resave: false,
saveUninitialized: true
}));
|
Now use flash in app.js file:
1
|
app.use(flash());
|
Now you can put your message in following way :
1
2
3
4
5
6
7
8
9
10
11
|
router.get('/destroy/:id', function(req, res) {
Post.findByIdAndRemove(req.params.id, function (err, project) {
if (err) {
req.flash('deletePostErrorMsg', 'Something went wrong while deleting post!');
res.redirect('/posts');
} else {
req.flash('deletePostSuccessMsg', 'Post deleted successfully!');
res.redirect('/posts');
}
});
});
|
and you can achieve the message by following code.
1
|
req.flash('deletePostSuccessMsg');
|
so you can render your messages to view like this
1
2
3
4
5
6
7
8
9
|
router.get('/', function(req, res) {
Post.find({}, function(err, projects) {
if (err) {
console.log(err);
} else {
res.render('posts', { deleteProjectSuccessMsg: req.flash('deletePostSuccessMsg'),deleteProjectErrorMsg: req.flash('deletePostErrorMsg'), posts: posts });
}
});
});
|
Now on view you can print the message like :
1
2
3
4
5
|
<% if (typeof deletePostSuccessMsg != 'undefined' && deletePostSuccessMsg) { %>
<div class="alert alert-success"><%- deletePostSuccessMsg %></div>
<% } else if(typeof deletePostErrorMsg != 'undefined' && deletePostErrorMsg) { %>
<div class="alert alert-danger"><%- deletePostErrorMsg %></div>
<% } %>
|
Here I’m using ejs template engine. ...