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:
mkdir session_demo
cd session_demo
express express_session
npm install
Once the basic express application is created we install express-session module with the command below:
npm install express-session--save
After this we must include this module in our app.js file.
var express = require('express');
var session = require('express-session');
var app = express();
After this we need to initialize the session:
app.use(session({secret: 'mysecret'}));
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('/');
});
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)