我知道有很多关于此问题的问题,但我已经研究我的问题一段时间了,而且建议的解决方案似乎都无法解决我的问题。
我正在开发一个网络应用程序。
在前端,我将 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 包交换。这些是请求和响应 header :
请求 header :
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
响应头:
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 的同时处理 session ,我最终选择了 JWT(JSON 网络 token )。
这是一篇带有解释和很好示例的文章:http://www.sitepoint.com/using-json-web-tokens-node-js/
感谢所有试图帮助我的人。
关于ajax - nodejs 中的 session 处理。 CORS问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29592235/