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
    • 197
    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:

      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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: