使用节点js和" connect-mongostore"进行会话存储

时间:2014-03-25 11:10:29

标签: javascript node.js session connect

我正在尝试使用带有“connect-mongostore”模块的节点js创建会话。我能够创建会话。但它没有正确存储它。

这是我的服务器端代码

//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);

每当在localhost中加载链接时,变量“value”的值就会递增。但是,同样不会保存在客户端。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

你在应用中听了两次

从底部删除app.listen,一切正常