socket.io和node.js在localhost上给出错误

时间:2014-05-27 05:56:58

标签: node.js socket.io

我有一个开发服务器在192.168.1.22上工作,我想在它上面运行node.js,但它给出了一些错误。我想只测试一些情况,但即使不能运行它。在我运行它后,我将获取我的onclick按钮,并从node.js发送该帖子到我的php文件。并将数据从php返回到node.js和node.js到网站。

我的js:

var http = require('http'),  
    io = require('socket.io'),

server = http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<h1>Sample server created with NodeJS.</h1>');
    res.end();
});
server.listen(8001);

// socket.io 
var socket = io.listen(server); 
socket.on('connection', function(client){ 
  client.send('Hello client'); 
  client.on('message', function(){
     client.send((new Date()).getTime());
  })
}); 

我的HTML:

  <script type="text/javascript" src="http://cdn.socket.io/stable/socket.io.js"></script>
  <script type="text/javascript">
    var socket = new io.Socket(null, {port: 8001});

    socket.connect();
    socket.on('message', function(message){
        document.getElementById('divTime').innerHTML = message;
    });     
    function GetServerTime() {
        socket.send('');
    }  
  </script>

错误:

WebSocket connection to 'ws://192.168.1.22:8001/socket.io/websocket' failed: Connection closed before receiving a handshake response socket.io.js:378
XMLHttpRequest cannot load http://192.168.1.22:8001/socket.io/xhr-polling//1401170092339. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.22:8000' is therefore not allowed access. (index):1
WebSocket connection to 'ws://192.168.1.22:8001/socket.io/websocket' failed: Connection closed before receiving a handshake response socket.io.js:378
XMLHttpRequest cannot load http://192.168.1.22:8001/socket.io/xhr-polling//1401170102339. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.22:8000' is therefore not allowed access. (index):1
WebSocket connection to 'ws://192.168.1.22:8001/socket.io/websocket' failed: Connection closed before receiving a handshake response 

1 个答案:

答案 0 :(得分:1)

从错误中,您似乎正在尝试从另一个端口连接到此服务器:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.22:8000' is therefore not allowed access. (index):1

您上面粘贴的服务器代码(标记为“my js”)看起来很好。安装socket.io软件包后,我可以在本地运行相同的代码。那么问题可能不是启动服务器代码,而是在启动后连接到它?如果是这样,您上面的错误指向same-origin policy问题。如果您在节点应用程序中托管HTML代码,在同一端口上运行,则不应该出现此问题。