【发布时间】:2013-01-06 04:17:28
【问题描述】:
我正在尝试跨域 socket.io,但我遇到了一个问题:
我总是收到XMLHttpRequest cannot load http://handsonwithnodejs.samarthwiz.c9.io/socket.io/1/?t=1358882710333. Origin https://c9.io is not allowed by Access-Control-Allow-Origin。
服务器代码:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(process.env.PORT);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.set('origins', '*:*');
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
在第 19 行 io.set('origins', '*:*');我尝试将 ':' 替换为 '*', 'https://c9.io', 'c9.io', 'https://c9.io/' 和 '.',有时我会添加类似 'c9.io/' 的内容
我收到警告“非法来源...”,但这只是与 cloud9 相关的问题。
客户端代码:
<html>
<body>
<script src="https://raw.github.com/LearnBoost/socket.io-client/master/dist/socket.io.js"></script>
<script>
var socket = io.connect('http://handsonwithnodejs.samarthwiz.c9.io');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>
我知道使用 github 获取我的脚本还不是最好的主意,但我想保持我的代码干净并且错误消息可读('socket.io.min.js' 中的所有内容都在第 2 行)
附: 1.我知道还有其他类似的线程,但它们并没有解决我的问题。 2. 请不要回复'只需将页面托管在与socket.io相同的服务器上'我需要它是跨域的。
【问题讨论】:
-
这很有趣,我一直试图通过弄乱 Origin xdomain 等来阻止使用我的 Socket.io 的其他域,但到目前为止还没有运气!我可以从任何地方 io.connect 到 MyIP:Port。现在你说你不能从其他域访问。请告诉我如何停止 CORS :)
标签: node.js cross-domain socket.io