Socket.IO - cannot load XMLHttpRequest in Google C

2019-07-21 11:55发布

问题:

I'm trying to get very first example from socket.io home page working in Chrome(19.0.1048.46) but I get the error:

"XMLHttpRequest cannot load http:// localhost:8080/socket.io/1/?t=1337156198176. Origin null is not allowed by Access-Control-Allow-Origin."

Server code:

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);
  });
});

Client code:

<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>

What is wrong with this code ?

回答1:

I believe you are opening the index.html file directly in the browser, is that the case?

With file:// protocol no origin is set to the XMLHttpRequest, so the browser will raise that security exception if the server doesn't set the Access-Control-Allow-Origin header enabling CORS

Navigate to http://localhost:8080/ instead, the handler specified in the code should render the index.html page correctly