简体   繁体   中英

session storage using node js and “connect-mongostore”

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?

You are listening two times in the app

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM