问题描述
所以,我创建了一个Apache代理我api.example.loc转发到本地主机:8080 / API
So i've created an apache proxy to forward my api.example.loc to localhost:8080/api
ServerAdmin [email protected]
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
and i'm having my nodejs server running and listening on port 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和放大器;&安培;相同的会话ID刷新时
when calling localhost:8080 or api.example.loc everything is okayi'm having the host api.example.loc && the same sessionID when refreshing
api.example.loc
BWqB8NtZ3beHXZchkxJvwvEB
但试图从其他域叫我api.example.loc的时候,可以说用ajax api.loc
but when trying to call my api.example.loc from an other domain, lets say api.loc using ajax
$.ajax({ url: 'http://api.livechat.loc/', crossDomain: true });
我遇到我每次刷新api.loc页面一个新的会话ID
i'm having a new sessionID each time i refresh the page on api.loc
api.livechat.loc
OcIGeviXOmCkBWRELzPqMmVu
api.livechat.loc
1yGT3rBaPaf9HCQ5zGd4iUud
我注意到,当调用api.example.come一个会话cookie主机api.example.loc创建的,但如果通过从api.loc阿贾克斯所谓的cookie被创建,所以我试了下,有没有更好的效果
i've noticed that when calling api.example.come that a session cookie is created on host api.example.loc, but no cookie is created if called through ajax from api.loc, so i've tried the next, with no better results
...
.use(require('express-session')({ secret: 's£cr£+c@d£', cookie: { domain: '.api.loc', path: '/', maxAge: 1000 * 60 * 24 } }))
...
什么想法?
推荐答案
确定我完成加入withCredentials到我的ajax调用这样的cookie可以被设置跨域
ok i finished by adding withCredentials to my ajax call so cookies can be set cross domain
$.ajax({ url: 'http://api.livechat.loc/', crossDomain: true, xhrFields: { withCredentials: true } });
和改变我的代理conf下的位置节
and changing the location section on my proxy conf to
<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>
这篇关于会话时,Ajax调用nodejs与Apache的mod_proxy并从不同的域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!