Can't load socket.io using node.js: io is not defined
I generated an express app by using express-generator and when including socket.io I've noticed that socket.io client is not being loading by the browser. I've been 2 days searching on the internet for a solution with no success.
I followed socket.io instructions for express 3/4 and in fact the socket.io client that is exposed by the server on /socket.io/socket.io.js is being served (no 404 errors). The problem is that when javascript code that tries to use socket io client fails because "io is not defined"
Any ideas about why the browser is not loading the client although it states that HTTP GET to http://localhost:8080/socket.io/socket.io.js returns HTTP 200?
By the way, the app is also using Angular.js.
index.html
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script type="text/javascript">
// Uncaught ReferenceError: io is not defined
var socket = io.connect('http://localhost:8080');
</script>
app.js (no error logs and socket.io server debug message says " socket.io:server serve client source +3s")
// setup server
app.set('port', process.env.PORT || 8080);
var server = require('http').Server(app);
var io = require('socket.io')(server);
console.log(app.get('port'));
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Update:
By using socket.io CDN the result is the same. It does not work
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
I'm answering my own question. I finally found a solution for this problem but I still don't know what was the cause.
The solution was to move <script src="/socket.io/socket.io.js"></script>
before any other tags (there are 16 script declarations: angular, bootstrap, jquery, moment, etc.).
So if you get "Uncaught ReferenceError: io is not defined" message on the browser move first "" at the beginning of the page inside tags . It will save you a lot of effort trying to make it work.
链接地址: http://www.djcxy.com/p/63188.html