socket.io, io is not defined (JS Error)

2019-02-11 12:52发布

问题:

I have just started with socket.io, its giving JS Error on client page

io is not defined

How to fix this ?

回答1:

put <script src="http://yournodeserver/socket.io/socket.io.js"></script> into your code



回答2:

Alternatively you can use the Socket.io CDN:

<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>


回答3:

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>


回答4:

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/



回答5:

<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.



回答6:

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.



回答7:

http://socket.io/download/ - the official page for latest cdn.