当ajax使用apache mod_proxy和不同的域调用nodejs时会话

所以我创build了一个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); 

当调用本地主机:8080或api.example.loc一切都好,我有主机api.example.loc &&相同的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一个会话cookie被创build在主机api.example.loc,但没有cookie创build如果从api.loc通过ajax调用,所以我试了下,没有更好的结果

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

有任何想法吗 ?

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

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

并更改我的代理conf的位置部分

 <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>