Vin*_*ent 2 session connect node.js cors express
我是使用Express和Connect的新手,所以我希望我做一些有点简单解决方案的蠢事......
基本上,我有一个用户使用Persona登录的页面.要验证身份验证尝试,我使用express-persona.据推测,该模块将用户经过验证的电子邮件地址保存在会话变量中(默认情况下为req.session.email).
现在,登录后,用户可以发表评论,此评论将与用户登录的电子邮件地址一起保存.当提供表单的服务器与处理评论发布的服务器相同时,这很好用.但是,当它们不同时(假设用户填写表单http://localhost:8001,而浏览器然后发送一个http://localhost:8000应该保存注释的POST请求),突然req.session.email值为undefined.
我想我正确设置了跨源资源共享.表格是这样发送的(使用jQuery):
$.ajax('http://localhost:8000/post/comment',
{
data: {comment: $('#commentField').val()},
type: 'POST',
xhrFields: {withCredentials: true}
}
);
Run Code Online (Sandbox Code Playgroud)
(注意xhrField: {withCredentials: true}- 会话cookie被传递,我通过检查网络请求来验证.)
服务器设置(我认为)正确的CORS头:
res.header('Access-Control-Allow-Origin', 'http://localhost:8001');
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');
res.header('Access-Control-Allow-Credentials', 'true');
Run Code Online (Sandbox Code Playgroud)
当我添加时console.log(req.cookie),我看到sessionIdcookie与POST请求一起发送的cookie具有相同的值.
但是: console.log(req.session.email)显示undefined跨源请求 - 再次,当请求来自同一源时,它可以正常工作.
我究竟做错了什么?
我发现了我的问题:我忘了发送带有身份验证请求的Cookie.因此,Express服务器在登录时无法识别当前用户的会话,因此无法将用户数据保存到会话中.
解决方案是还发送带有withCredentials标志的Persona断言请求,如下:
var response = $.ajax(assertionUrl + '/verify', {
data: {assertion: assertion},
type: 'POST',
xhrFields: {withCredentials: true}
});
Run Code Online (Sandbox Code Playgroud)
(我认为没有人会碰到这个完全相同的问题,但以防万一...)
| 归档时间: |
|
| 查看次数: |
3035 次 |
| 最近记录: |