Simcha
Simcha

Reputation: 3400

Session in nodejs

sorry for newby question, but can you explain me how to use sessions in nodeJS. I read a lot of articles in internet but I didn't success to implement something for my purpose (data is saving the session, but every new request session is empty), can you give example from the beginning how to initialize and how to use.

Purpose: when user do login in the system, I need to open session for him and every request that he will send in the future I need to check is his session exist?

I'm using express 4.x. I do it like:

// init session
app.use(cookieParser());
app.use(session({
  secret : "yepiMobileSession",
  resave : true,
  key : "session",
  store: mongooseSession(daoService.mongoose), 
  saveUninitialized : true
}));


// save user to the session
request.session[CONST.SESSION_USER] = user;

// Check login
function checkLogin(id){
        var user = request.session[CONST.SESSION_USER];
        if (user && request.params.clientData && user._id == id){
            return true;
        } else {
            return false;
        }
    }

Upvotes: 0

Views: 1686

Answers (1)

Asis Datta
Asis Datta

Reputation: 563

You can take a look at the following code. I think this will help you.

var app = require('express')(),
    expressSession = require('express-session'),
    cookieParser = require('cookie-parser');

app.use(cookieParser());
app.use(expressSession({
    secret: 'mYsEcReTkEy',
    resave: true,
    saveUninitialized: true
}));// I haven't used the session store

//setting session

app.post('/login', function(req,res){
  var id=12345;
  req.session.userId = id;
  res.send(200);
});

//getting session

app.get('/hello', function(req,res){
  var id=req.session.userId;
  console.log("Hello",id);
  res.send(200);
});

But node server and client have to be in same domain.

Upvotes: 2

Related Questions