我試圖做跨域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
。Socket.io跨域連接失敗; 'XMLHttpRequest無法加載...'
Server代碼:
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上得到我的劇本是不是最好的主意,但我想保持我的代碼清潔和錯誤信息可讀(一切都在「插座。 io.min.js'在線2)
PS 1.我知道還有其他類似的線索,但它們並沒有解決我的問題。 2.請不要回復'只需將該頁面託管在與socket.io相同的服務器上'我需要它是跨域的原因。
這很有趣,我一直試圖阻止其他域使用我的Socket.io雜亂的Origin xdomain等等,到目前爲止沒有運氣!我可以從任何地方連接到MyIP:端口。現在你說你不能從其他域訪問。請告訴我如何停止CORS :) – Maziyar