1

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

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
4

1 回答 1

4

我解决了这个问题,我从其他来源和 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);
        });
于 2015-12-17T12:39:59.587 回答