Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Express-session in Node.js

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 575
    Comment on it

    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:

    1. mkdir session_demo
    2.  
    3. cd session_demo
    4.  
    5. express express_session
    6.  
    7. npm install

    Once the basic express application is created we install express-session module with the command below:

     

    1. npm install express-session--save

    After this we must include this module in our app.js file.

    1. var express = require('express');
    2. var session = require('express-session');
    3. var app = express();

    After this we need to initialize the session:

    1. app.use(session({secret: 'mysecret'}));

    Now using request object we can assign session to any variable.

    1. app.get('/', function(req, res){
    2. // here we are accessing the userName from session
    3. if(req.session.userName){
    4. res.render('home', { user_session: req.session.userName });
    5. }
    6.  
    7. });
    8.  
    9.  
    10. app.post('/', function(req, res){
    11. // Here we are assining the the value to the session
    12. req.session.userName = req.body.userName;
    13. res.redirect('/');
    14.  
    15. });

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: