express-session不保存nodejs

时间:2015-12-17 00:06:04

标签: node.js session express-session

这个简单的例子不起作用。在会话的每个请求中 再次创建,我不知道如何解决它。

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

app.use(expressSession({
    secret:'secret',
    resave:true,
    saveUninitialized:true,
    cookie:{
        httpOnly:false,
        expires:false
    }
}));

app.all('/',function(req,res,next){
    var session = req.session;
    if(session.count){
        session.count++;
    }
    else{
        session.count = 1;
    }
    console.log('id:',req.sessionID);
    console.log('count:',session.count);
    res.end();
});

app.listen(9090);
console.log('server is running at http://localhost:9090');

我尝试保存请求数,但会话已创建 每当我提出请求时。

//request
>GET http://localhost:9090

//response
id: gOqbVisxaW34qafRdb7-6shqYV0UurRg
count: 1


//request again
>GET http://localhost:9090

//response
id: P2iyXKHElJF8u86tHu7mIl7Encteebju
count: 1

1 个答案:

答案 0 :(得分:3)

我解决了这个问题,我从其他来源和ajax提出了请求。我在服务器上添加了以下中间件:

app.use(function (req, res, next) {
            // Website you wish to allow to connect
            res.setHeader('Access-Control-Allow-Origin', req.headers.origin);

            // Request methods you wish to allow
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
            // Request headers you wish to allow
            res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
            // Set to true if you need the website to include cookies in the requests sent
            // to the API (e.g. in case you use sessions)
            res.setHeader('Access-Control-Allow-Credentials', 'true');
            // Pass to next layer of middleware
            next();
        });

在ajax请求中我在xhrFields中添加了 withCredentials 选项

 $(document).ready(function(){
            setInterval(function(){
                $.ajax({
                    url:'http://localhost:9090/',
                    type:'post',
                    dataType:'json',
                    success:function(data){
                        console.log(data);
                    },
                    xhrFields:{
                        withCredentials:true
                    }
                });
            },1000);
        });