Socket.IO - 无法在Google Chrome中加载XMLHttpRequest

mic*_*uza 2 node.js socket.io

我试图从Chrome(19.0.1048.46)中的socket.io主页获得第一个例子,但是我得到了错误:

"XMLHttpRequest无法加载http:// localhost:8080/socket.io/1 /?t = 1337156198176.Access-Control-Allow-Origin不允许使用Origin null."

服务器代码:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8080);

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.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
Run Code Online (Sandbox Code Playgroud)

客户代码:

<script src="socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:8080');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });    
  });
</script>
Run Code Online (Sandbox Code Playgroud)

这段代码有什么问题?

BFi*_*Fil 5

我相信你是直接在浏览器中打开index.html文件的,是这样吗?

使用file://协议,没有源设置为XMLHttpRequest,因此如果服务器未设置启用CORS 的Access-Control-Allow-Origin标头,浏览器将引发该安全性异常

导航到http:// localhost:8080 /,代码中指定的处理程序应正确呈现index.html页面