Session 在 nodejs 中处理。 CORS问题

Session handling in nodejs. CORS issue

我知道有很多关于这个问题的问题,但我研究我的问题已经有一段时间了,none 的建议解决方案似乎解决了我的问题。

我正在开发 Web 应用程序。

在前端,我将 AJAX 请愿书扔到后端,用 nodejs 开发。

在后端,我正在尝试使用 express.js 中间件处理用户 session。

我无法使 session 工作。

我认为这是 AJAX 请愿书的问题,但根据我的阅读,我应该能够用这些请愿书创建 cookie,所以我不知道该怎么想。

在我的后端,我使用中间件来处理 CORS 问题。这是代码:

var enableCORS = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Cookie');
    res.header('Access-Control-Allow-Credentials', true);

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
      res.status(200).send('');
    }
    else {
      next();
    }
};


app.use(enableCORS);

然后,当我处理实际的请愿书时,我会尝试这样处理session:

req.session.field = 'value';

问题是,我没有收到以下请愿书的任何 session 信息。

我一直在仔细研究这个问题。我正在使用的 AJAX 请愿书的一个例子是这个:

$.ajax({
            url: 'http://example.com/resource',
            type: 'get',
            dataType: 'json',
            async: true,
            crossDomain: true,
            beforeSend: function(xhr){ xhr.withCredentials = true; },
            success: function(x, status, xhr){
              console.log(x);
            },
            error: function(xhr, status, error){ }
          });

我一直在浏览器的网络部分观看 http 包交换。这些是请求和响应 headers:

请求Headers:

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,es;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:29
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:example.com
Origin:http://example.net
Pragma:no-cache
Referer:http://example.net/
User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36

响应Headers:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Authorization, Content-Length, X-Requested-With, Cookie
Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Length:96
Content-Type:application/json; charset=utf-8
Date:Sun, 12 Apr 2015 16:32:36 GMT
Server:Cowboy
Set-Cookie:connect.sid=s%3A7OCuaEWUjkpdOrxFuNo6KrtpnS_e5SpZ.S2O4PIVy2YkKuLxQ9KuzfcaszRZzqq5hjL3PfaHrQBw; Path=/; Expires=Sun, 12 Apr 2015 17:22:36 GMT
Vary:X-HTTP-Method-Override
Via:1.1 vegur
X-Content-Type-Options:nosniff
X-Powered-By:Express

在响应中实际上发送了 Set-Cookie header,但我的浏览器中没有创建 cookie,因此以下请愿不会携带该信息。

我敢肯定这是一些愚蠢的细节,但我就是不能指手画脚。

提前致谢!

好吧,我找到了一个替代方案,所以我正在回答我自己的问题。

首先,根据我的阅读,没有办法用 cookie 做我想做的事情。

因此,为了在能够使用通配符实现 cors 的同时处理会话,我最终选择了 JWT(JSON 网络令牌)。

这是一篇带有解释和很好示例的文章:http://www.sitepoint.com/using-json-web-tokens-node-js/

感谢所有试图帮助我的人。