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

我有一个开发服务器在192.168.1.22上工作,我想运行node.js,但它会给出一些错误。 我只想testing一些情况,但是甚至不能运行它。 运行后,我将获取我的onclickbutton,并从node.js发送到我的PHP文件的post。 并从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 

从错误,它看起来像你试图从另一个端口连接到这个服务器:

 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 

上面粘贴的服务器代码(标记为“我的js”)看起来不错。 一旦我安装了socket.io包,我就可以在本地运行相同的代码。 所以也许问题不是启动那个服务器代码,而是一旦启动就连接到它? 如果是这样,上面的错误指出了同样的政策问题。 如果您从运行在同一端口上的节点应用程序托pipeHTML代码,则不应该有此问题。