Mar 12, 2014

How to create a Session Variable in Node.js & Express?



In this post we will create a session variable that would allow us to access a website through a password. It's simple and only ones programs we need to have installed on our computer are Node.js and Express. If you do not have installed you can see how to do it here:




          - Node.js       (If you don't have it click here)
          - Express      (If you don't have it click here)

Now, we will create our project:



Create the project

1 - Open your terminal and headed to the directory where we want to create our project

2 - Write in the terminal:    $ express -s appSession  

       The "-s" causes that Express initialize and configure the session variables. if you see "app.js" have 2 new uses (app.use(express.cookieParser('your secret here')); app.use(express.session());

3 - choose de folder of the project in the terminal:    $  cd appSession  

4 - install dependencies, write in the terminal:   $ npm install  



Create the Routes

Open the file "app.js" and add this code below "app.get('/users', user.list);":


// ... code

app.get('/', routes.index);
app.get('/users', user.list);

//Create the route to login page
app.get('/login',function(req,res){
        res.render('login', { 
             title: 'Login'
       });
});

//Create the route to verification for login page
app.post('/login',function(req, res){
         // If de password is "admin"...
         if (req.body.password == "admin")
         {
                  // save the user in the session variable
                  req.session.user = req.body.user;
                  res.redirect('/secret');
         }
});

//Create the route to secret pageapp.get('/secret',function (req,res){
      // if exist the user in session variable ...
      if (typeof(req.session.user) != "undefined")
      {
             // redirect to secret page
             res.render('secret',{
                     title:'secret',
                     user: req.session.user
             });
      }
      else
     {
           // else redirect to login page
           res.redirect('/login');   
     }
});

// ... code


Create the views

Open the jade file "views/index.jade" and write a link to secret page "a(href="/secret") go to Secret".

becareful with the tabulated, jade is very sensitive with them

Create a new jade file "views/login.jade" and write this:

becareful with the tabulated, jade is very sensitive with them


Create a new jade file "views/secret.jade" and write this:

becareful with the tabulated, jade is very sensitive with them



Run de App

Write in the terminal:   $ node app  and open your browser in localhost:3000/



I hope you liked it, and if you have any questions feel free to write me:




No comments:

Post a Comment