Socket.io with a local client. The origin of null and Access-Control-Allow-Origin

I am trying to test a simple socket.io example with a local client. Here is my code:

Server:

var sio = require('socket.io'); var io = sio.listen(8077, {log: false}); io.sockets.on('connection', function (socket) { console.log('connection detected'); socket.on('hello', function(data){ console.log('hello received: ' + data); }); }); 

customer:

 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="socket.io-client/dist/socket.io.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> var socket = io.connect('http://localhost:8077'); if(socket != undefined){ socket.emit('hello', 'this is a test'); } </script> </body> </html> 

If I put my client on a remote server, it works fine, but if I try to start my client from local, my browser will give me the following error:

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

I know there is an HTTP header that solves this problem on the http server, but I do not know if there is a similar option in the socket context. I need a local client. I do not want to serve client code from an additional nodejs http server.

+4
source share
1 answer

Have you tried setting the server source parameter (it sets the header you mentioned)?

 var sio = require('socket.io'); var io = sio.listen(8077, {log: false, origins: '*:*'}); 

In addition, now that you have not accessed this server locally, you must have updated the line:

 var socket = io.connect('http://localhost:8077'); 

enable ip (or domain, if you have one) of the remote server:

 var socket = io.connect('http://XX.XX.XX.XX:8077'); 

You see which line returns an error in the console (are you using chrome / ff with firebug?). In an if statement, the socket variable will probably never be undefined. The recommended way to use a connection is to wait for it to be ready by adding a callback to the connect event, for example:

 socket.on('connect', function () { // <-instead of the if socket.emit('hello', 'this is a test'); } 
+4
source

All Articles