0

In running an express app, the Jade template includes two script lines:

  script(src="https://cdn.socket.io/socket.io-1.3.5.js")  <== library
  script(src="main.js")                                   <== my code

But when I call something defined in the first script from my JavaScript in main.js, I get the error:

 Uncaught TypeError: Cannot read property 'connect' of undefined

The offending line is this one:

 var io = io.connect();

Which is defined in the first socket.io script. How can I include that script in a way that my code in main,js can find it?

If this was server side, I'd just 'require' it.

2 Answers 2

1

Try this version

https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js

https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js

Socket io use browserify in order to compile the script into one file.

Probably the version you use is corrupt. If this doesn't solve, try to use the npm socket-io.client lib.

npm install --save socket.io

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>

Translate this into jade.

Sign up to request clarification or add additional context in comments.

3 Comments

The first idea does not change things. I'll try the 'translate into Jade' option.
Rember to install it in the node server that run socket io
I'm using express.io, so it should be installed by default.
1

Regarding accessing the io javascript
You can check in your developer tools in network or console tab to find if the socket js is loading in your templates.

you can install it with node:

npm install socket.io    
var io = require('socket.io')(80);

Other than that you can go directly to this page https://cdn.socket.io/socket.io-1.3.5.js and copy the code from that page into a local js file (socket.js or whatever you'd like to call it) and then require it as you would any other file.

Or find a different cdn to try and access it from.

Regarding the error you are getting
Have you defined io anywhere?

7 Comments

I'm not sure I understand your question. Isn't it defined in the included file (the one that I infer is not being loaded)?
Okay but the issue here is youre calling .connect() on an io object that you havent defined. You are defining io = io.connect() but the io in io.connect() hasnt been defined. if you get me.
The io object is the default global exported object of the lib socket.io. You can check this in the documentation of socket.io
yes which is usually defined like this var io = require('socket.io')(80); but you havent defined io in your code so you cant call methods on it.
That helps. So where do I define it? This is client side code, so I can't just require it, right?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.