Socket.IO - require is not defined

2019-02-02 09:34发布

I'm trying to get socket.io working but now in Chrome I get the error:

Uncaught ReferenceError: require is not defined

client.php:9Uncaught ReferenceError: io is not defined

I changed the way to include the socket.io.js file because it dosnt exists somewher else:

<script src="/node_modules/socket.io/lib/socket.io.js"></script>

If I try

<script src="/socket.io/socket.io.js"></script>

I get: Failed to load resource: the server responded with a status of 404 (Not Found)

This is on Ubuntu with the latest of everything

I'm using the server code from http://socket.io/ to work with in the same folder like client.php and that works, named server.js, only modified port.

8条回答
ゆ 、 Hurt°
2楼-- · 2019-02-02 10:11

As others have noted, when io is run on the server side, an "automagical" service of "socket.io.js" is served - and it branches out to the other js files in its lib directory.

What I wish to add, is that This is Not Intutive and, no, you cannot have your regular webserver serve this file - the errors just get more strange and seemingly contradictory (require not defined, etc). This is not a normal js file, and I wish all the tutorials out there would emphasize that.

Anyhow, if you are running behind nginx, for example, set the port-settings to the same port assigned for node - port 3000 in my case. I used that port in the client like this:

  <script src="http://localhost:3000/socket.io/socket.io.js"></script>

... and then also used port 3000 in the server code - there are too many ways / versions you can code the server-js-code for an example to do anything but confuse most who are using 'a different way'.

查看更多
Rolldiameter
3楼-- · 2019-02-02 10:12

I tried what thejh says and it works. I needed to specify the host and port. For a node app listening on port 81, I needed to specify port 81 in the client javascript. Nevermind /socket.io/socket.io.js doesn't exist in the vhost, node makes up for it at runtime.

查看更多
登录 后发表回答