今天用官网的例子测试了socket.io,官网的例子很ok,但是在我改了监听端口后,就开始报错了
服务器端:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8081, function(){
    console.log('start listen...')
});
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.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
客户端:
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
但是我在改了服务端的监听端口不是80后,客户端就报错了
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1433127576223-189 
(index):1 XMLHttpRequest cannot load http://localhost/socket.io/?EIO=3&transport=polling&t=1433127576223-189. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access. The response had HTTP status code 404.
不知道这是什么错误呢?
      5 回复
    
    http://127.0.0.1 和 脚本中的var socket = io(‘http://localhost’); 在浏览器视为不同域的,改为同一种即可。 一般如果要在生产环境测试,最好绑hosts这样可以避免各种因为localhost的域导致的比较隐蔽的问题。
 
    