node.js本地正常服务器端报错的解决方案

这其实就是个跨源调用问题,网上的demo都只是在本地可以运行,一旦放到node云上websocket就跪了,我花了两天时间都找不到解决方案,今天去stackoverflow上搜了一下一下子就知道问题所在了,只要把io.connect(url)中的url设为空即可!!!极力推荐 stackoverflow这个网站,程序猿必备良站!

原文请见http://stackoverflow.com/questions/11916999/socket-io-only-works-locally

/*******************************************以下是原文*********************************************************/

I have this Node.JS server:

CLIENT SIDE CODE:

The problem is that it seems to be only working locally. On ubuntu chrome I get:

2 Answers

A site’s domain doesn’t have to do with where it is hosted, it has to do with what domain you are using to access it.

Even if “192.168.1.130” and “localhost” resolve to the same server, they are considered different domains.

As a result, because you have the client side code:

You are connecting to the domain localhost. If the client code was served by localhost you’re fine, but if you are loading the client from another domain (for example 192.168.1.130) then you’ll face problems. From the browser and server’s perspective you could easily be a complete stranger trying to access that service.

To fix the problem change the client side socket creation to:

var socket = io.connect('192.168.1.130');

You should have your problem resolved.

Really though, you should just remove the parameter completely and try running:

var socket = io.connect();

That way it will default to whatever domain you are based on, and it will work both on localhost, the IP, and eventually the domain name you use.

answered Aug 11 ’12 at 22:41
slifty
1,6641629
oh boy… sooo stupid!!! totally forgot about that… my question is worth a delete shah – user1130217 Aug 11 ’12 at 22:44
No it’s an easy mistake to make! The question will help others facing similar problems. – slifty Aug 11 ’12 at 22:47

Change the app.listen(80) to app.listen(80, ‘192.168.1.130’) for it to use that IP, that way your URLs from socket.io should be correct. Also be sure to access it from 192.168.1.130 in your browser even if you try it on the local machine.

answered Aug 11 ’12 at 19:51
Clarence
1,01816
no luck.. still the same error. also I don’t think it’d be a good idea to put the local IP as I would like my server to be accessible from outside my intranet. – user1130217 Aug 11 ’12 at 19:59
thnx man your suggestion solved my problem 🙂 – Mj1992 Feb 16 at 11:03