I have just started with socket.io, its giving JS Error on client page
io is not defined
How to fix this ?
I have just started with socket.io, its giving JS Error on client page
io is not defined
How to fix this ?
put <script src="http://yournodeserver/socket.io/socket.io.js"></script>
into your code
Alternatively you can use the Socket.io CDN:
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
I faced the same problem when using express. Even putting the server:port inside the script would not work.After the server started i would make socket listen to that port, that was mistake i guess.Changing it to below works fine
var app = express();
app.set('port', process.env.PORT || 3000);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'));
On Client side I just include the script
<script src="/socket.io/socket.io.js"></script>
I have a socket app where my server (not a CDN) is serving up the socket.io.js script. So, while Emmerman is right in saying that you need to include the script tag in your client HTML code, the asset won't be loaded if your back-end is down. One option is for you to write a client-side JS script that checks for io before you try and use socket.io. If it's not present (undefined/null) then you can either conditionally show something else like, "server down" or in my case, I'm going to set a timer that keeps checking periodically until the server is restored.
[UPDATE 2] Ended up having to include the script tag, check for existence of io
object and doing a window.location.reload() after 10 seconds (using setTimeout
) (which eventually will hopefully find that the script loaded and io
exists, after which I can connect to the socket server.)
[UPDATE] I'm loading the script with an ajax call rather than using an html script tag. Then with the timer I'm checking periodically if the script will load – eventually it will when the server is restored/rebooted. jQuery ref to load JS scripts dynamically: http://api.jquery.com/jQuery.getScript/
<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
this is the latest version of socket.io to be included.
Wrap your client code on a '$(document).ready()' for jQuery or another library similar function. This way you'll be sure your code runs after the library beeing loaded.
http://socket.io/download/ - the official page for latest cdn.