Socket.IO - cannot load XMLHttpRequest in Google Chrome

允我心安 提交于 2020-01-15 04:29:07

问题


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



来源:https://stackoverflow.com/questions/10614857/socket-io-cannot-load-xmlhttprequest-in-google-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!