当ajax使用apache mod_proxy从另一个域调用nodejs时的会话

时间:2014-06-10 14:55:14

标签: ajax node.js apache cookies express

所以我创建了一个apache代理来将我的api.example.loc转发到localhost:8080 / api

ServerAdmin webmaster@example.loc
ServerName api.example.loc

ProxyRequests off
ProxyPreserveHost On

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

<Location />
    Header set Access-Control-Allow-Origin "*"

    Order allow,deny
    Allow from all

    ProxyPass http://localhost:8080/api/
    ProxyPassReverse http://localhost:8080/api/
    ProxyPassReverseCookiePath / /
</Location>

我让我的nodejs服务器在端口8080上运行和监听

var express = require('express'),
app = express(),
server = require('http').createServer(app),

app
.use(require('cookie-parser')())
.use(require('express-session')({ secret: 's£cr£+c@d£' }))
.get('/api', function(req, res) {
    var host = req.get('host');

    console.log(host);
    console.log(req.sessionID);
});

server.listen(8080);

调用localhost:8080或api.example.loc时一切正常 我有主机api.example.loc&amp;&amp;刷新时的相同sessionID

api.example.loc
BWqB8NtZ3beHXZchkxJvwvEB

但是当尝试从其他域调用我的api.example.loc时,可以使用ajax说api.loc

$.ajax({ url: 'http://api.livechat.loc/', crossDomain: true });
每次刷新api.loc上的页面时,我都会有一个新的sessionID

api.livechat.loc
OcIGeviXOmCkBWRELzPqMmVu

api.livechat.loc
1yGT3rBaPaf9HCQ5zGd4iUud

我注意到,在调用api.example.come时,在主机api.example.loc上创建了一个会话cookie,但是如果通过api.loc中的ajax调用则不会创建cookie,所以i&#39;我尝试了下一个,没有更好的结果

...
.use(require('express-session')({ secret: 's£cr£+c@d£', cookie: { domain: '.api.loc', path: '/', maxAge: 1000 * 60 * 24 } }))
...

任何想法?

1 个答案:

答案 0 :(得分:0)

好吧我完成了将withCredentials添加到我的ajax调用中,因此可以跨域设置cookie

$.ajax({ url: 'http://api.livechat.loc/', crossDomain: true, xhrFields: { withCredentials: true } });

并将我的代理配置文件中的位置部分更改为

<Location />
    Header set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, PATCH, DELETE"
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Headers "X-Requested-With"
    Header set Access-Control-Max-Age "60"
    Header set Access-Control-Allow-Credentials true

    Order allow,deny
    Allow from all

    ProxyPass http://localhost:8080/api/
    ProxyPassReverse http://localhost:8080/api/
    ProxyPassReverseCookiePath / /
</Location>