5

I am trying to create a session using node js with "connect-mongostore" module. I am able to create the session. But it is not storing it correctly.

This is my server side code

//loading all the dependencies    
var express = require('express');
var app = express();
var MongoStore = require('connect-mongostore')(express);
var mongo = require('mongoose');

//my data base path to store sessions
var conf = {
    db: {
        db: 'mongoservernew',
        host: 'localhost',
        collection: 'mySessions'
    },
    secret: '076ee61d63aa10a125ea872411e433b9'
};

//configuration
app.configure(function(){
    app.use(express.cookieParser());
    app.use(express.session({
        secret: conf.secret,
        maxAge: new Date(Date.now() + 3600000),
        store: new MongoStore(conf.db)
    }));
    app.use(app.router);
});

//data base Url for storing data
var dbUrl = 'mongodb://localhost/mongoservernew';
mongo.connect(dbUrl);
mongo.connection.on('open', function () {
    app.listen(3002);
    console.log("connection open");
});


//creating a session and sending back to client side.
app.get('/', function(req, res) {
    console.log("global load");
    var previous      = req.session.value || 0;
    req.session.value = previous + 1;
    res.end('<h1>Previous value: ' + previous + '</h1>');
    res.send(req.session);
});

//creating cookies for each event.
app.get("/request",function(req,res){
    console.log("request received");
    console.log(req.session);
    var m=req.session.isLogged || 0;//isLogged is stored in session over here
    req.session.isLogged = m+1;
    console.log(req.session.isLogged);
});

app.get("/getsession",function(req,res){
    console.log("getsession received");
    console.log(req.session);
    console.log(req.session.isLogged);//but over here isLogged is returning undefined
})

app.listen(process.env.PORT || 3001);

Whenever the link is loaded in localhost, the value of variable "value" is incremented. But, the same is not saved in the client side. Can someone help me out?

aynber
  • 22,380
  • 8
  • 50
  • 63

1 Answers1

0

You are listening two times in the app

remove the app.listen from the bottom and everything works fine

Nisanth Sojan
  • 1,099
  • 8
  • 21