socket.io – require is not defined, io is not defined errors

Lately I have been woking on socket.io, trying to learn what it is all about and how to use it.

This is what I did on my local machine trying to get a simple app to work:

-Installed node.js from http://nodejs.org/ (on 64-bit win8)
-Installed socked.io module on node.js using npm (node package manager) (http://socket.io/#how-to-use)
-Quickly created a sample application using node
-Started node server
-Opened my index.html file

BAM! I got these 2 errors on chrome javascript console:
require is not defined
io is not defined

I was following some examples and everything seemed right to me but there was one thing that I had done different from the samples I had inspected on the net. These samples showed the reference to socket.io.js as below:

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

But when I checked the socked.io installation I saw no “socket.io” folder with “socket.io.js” file in it, so I thought they were using older versions of socket.io and/or node.js in the samples, and I decided to change the “socket.io.js” reference as below:

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

Because that was where socket.io.js file was. Apparently I was wrong!

You have to explicitly state host, port and socket.io directory, because socket.io.js file is served from the node server that way.

Hope this helps someone.

Good luck,
Serdar.

Leave a Reply

Your email address will not be published. Required fields are marked *