setting the cookie in a session

Tag: cookies , express Author: pengjiang123456789 Date: 2012-12-09

I am setting a cookie and access it. when I do console.log it does not show anything. but when I see the cookie on the browser I could see tha value. I want to check if the cookie is 1. if it is one continue else drop it. but I am having issue accessing this value.

2) Looks I am actually setting the value directly, than how is : app.use(express.cookieParser('keyboard cat')); useful here. the issue is if I dont have this app.use, it will fail unable to find the secret.

it wil be good if you can let me know what I am missing any pointers on cookies in express urls.

app.post('/login', function(req, res){

console.log(req.cookies.rememberme);
console.log(req.session.user);
if (req.session.user) {
    req.session.user=req.body.username;
    ss=req.session.user;
    res.cookie('rememberme', '1', { maxAge: 2000, httpOnly: true });
  } else {
    req.session.user="test";
    ss=req.session.user;
  }
res.send('viewed  times\n'+ss);
}); 

All I am looking is if a user has given a correct username and password than I will assign a cookie for him. if that is done and in subsequent request users will use the same cookie. I am also looking at how I can store this cookie in local memory and..

Other Answer1

This snippet exhibits how we can use cookie-based session !!

var express = require('express')
  , app = module.exports = express()
  , utils = require("util");

app.use(express.cookieParser('hello !!'));
app.use(express.cookieSession({key:"remember", secret: 'testing', cookie: { maxAge: 5000}}));
app.use(express.bodyParser());

app.get('/', function(req, res, next){   

  if(req.session.user) {
     res.send('welcome ' + req.session.user + ' Click to <a href="/forget">forget</a>!.');
  } else {
      res.send('<form method="post">'
      + '<p>Username : <label><input type="texst" name="user"/></label>'
      + '<p><label><input type="checkbox" name="remember"/> remember me</label></p> '
      + '<p><input type="submit" value="Submit"/>.</p></form>');
  }

});

app.get('/forget', function(req, res){
  res.clearCookie("remember");
  res.redirect('back');
});

app.post('/', function(req, res){

  if (req.body.remember) { 
    req.session.user = req.body.user;
    console.log ( "set-cookie :" , res.get("Set-Cookie"));    
  }    
  res.redirect('back');
});

if (!module.parent){
  app.listen(3000);
  console.log('Express started on port 3000');
}