我正在尝试跨域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行)
P.S。我知道还有其他这样的线程,但它们没有解决我的问题。 2.请不要回复'只需将页面托管在与socket.io相同的服务器上'我需要它是跨域的原因。
答案 0 :(得分:0)
我认为您需要在托管客户端代码时设置Access-Control-Allow-Origin标头。有关标题的更多信息,请查看https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS。
出于安全原因,必须由客户端设置此标头。