使用NodeJS-Socket.io构建我的应用时遇到跨域问题。
这是我的服务器:
console.log("Starting server...")
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
compress = require('compression')(),
sqlite3 = require('sqlite3');
app.use(compress);
app.disable('x-powered-by');
app.use(function (req, res, next) {
console.log('Setting configuration');
res.setHeader('Access-Control-Allow-Origin', "http://fo-member.dev.game.com");
res.setHeader('Access-Control-Allow-Origin', true);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
}
);
server.listen(11081);
io.set("origins","http://fo-member.dev.game.com");
console.log("Server started listening on 11081");
它在端口11081上运行。我已将apache配置为从端口80转发到节点服务器,如:
NameVirtualHost fo-node.dev.game.com:80
<VirtualHost fo-node.dev.game.com:80>
ServerName fo-node.dev.game.com
ServerAdmin contact@game.com
ErrorLog "logs\game-fo-node.error.log"
CustomLog "logs\game-fo-node.access.log" common
ProxyRequests Off
ProxyPreserveHost On
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location />
ProxyPass http://localhost:11081/
ProxyPassReverse http://localhost:11081/
</Location>
</VirtualHost>
我有一个在11080(它是tomcat)上运行的前端服务器,并且还是域上的apache的forware端口:http://fo-member.dev.game.com
在前端,我可以通过以下方式获取socket.io/socket.js:
<script type="text/javascript" src="http://fo-node.dev.game.com/socket.io/socket.io.js"></script>
现在看起来很好。但是当我从前端执行连接操作时,例如:
var socket = io.connect('http://fo-node.dev.game.com/notify');
socket.on("connect", function() {
console.log("connected");
// Let the server know who is connected...
socket.emit("user", { Id: 101 });
});
socket.on('update', function (data) {
// Do something cool like update badges/status/etc...
console.log(data);
});
客户端控制台显示错误:
XMLHttpRequest cannot load http://fo-node.dev.game.com/socket.io/?EIO=2&transport=polling&t=1401700586028-90. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.
此外,我已经在apache中添加了头配置允许跨域:
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www.)?(fo-member.dev.game.com|fo-rest.dev.game.com|fo-node.dev.game.com)$" AccessControlAllowOrigin=$0$1
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>
这是请求标题:
Request URL:http://fo-node.dev.game.com/socket.io/?EIO=2&transport=polling&t=1401703622820-0
Request Headers CAUTION: Provisional headers are shown.
Origin:http://fo-member.dev.game.com
Referer:http://fo-member.dev.game.com/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
Query String Parametersview sourceview URL encoded
EIO:2
transport:polling
t:1401703622820-0
我感谢你的阅读,也许你们可以让我知道我的错误。