over 8 years ago
For any web application session handling is very important part.Using sessions we can easily track user's activity throughout the application.
If we are using express in our node application, setting up a session becomes very easy.
Here we use express-session, which is a middleware for session handling.
Let start with creating an application using express generator:
Once the basic express application is created we install express-session module with the command below:
After this we must include this module in our app.js file.
After this we need to initialize the session:
Now using request object we can assign session to any variable.
app.get('/', function(req, res){
// here we are accessing the userName from session
if(req.session.userName){
res.render('home', { user_session: req.session.userName });
}
});
app.post('/', function(req, res){
// Here we are assining the the value to the session
req.session.userName = req.body.userName;
res.redirect('/');
});
app.get('/', function(req, res){
// here we are accessing the userName from session
if(req.session.userName){
res.render('home', { user_session: req.session.userName });
}
});
app.post('/', function(req, res){
// Here we are assining the the value to the session
req.session.userName = req.body.userName;
res.redirect('/');
});
Here you should have a home template in your view directory, where the value of session can be accesses via user_session variable.
0 Comment(s)