快速会话不保存nodejs

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

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

我试图保存请求的数量,但会话是在我每次提出请求时创build的。

 //request >GET http://localhost:9090 //response id: gOqbVisxaW34qafRdb7-6shqYV0UurRg count: 1 //request again >GET http://localhost:9090 //response id: P2iyXKHElJF8u86tHu7mIl7Encteebju count: 1 

我解决了这个问题,我提出了来自其他来源和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 (eg in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', 'true'); // Pass to next layer of middleware next(); }); 

并在ajax请求我把一个选项与xhrFieldsCredentials

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