An intern has no name An intern has no name - 1 year ago 90
Node.js Question

Error 404 when trying to get socket.io

I am writing a node server that serves a web page using socket.io. But when I load the page, the console shows the error


(index):6 GET http://localhost:3000/socket.io/socket.io.js


which is, unsurprisingly, followed by :


(index):51 Uncaught ReferenceError: io is not defined


when I examine the files loaded by the page in the network tab, it shows an error 404 for socket.io. But surprisingly, when I launched other programs I made that use socket.io, all worked fine. The only difference is that for this one, I use express.

Here is my code :

app.js :

var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

app.use(express.static("./app"));

app.get("/", function(req, res, next) {
res.sendFile(__dirname + "/index.html")
});

app.listen(3000);
console.log("Server started in http://localhost:" + 3000);


io.on('connection', function(socket){
socket.emit('news', {hello :'world'});
socket.on('my other event', function(data){
console.log(data);
});
});


index.html :

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>

[Some unrelated text]

<script>
var socket = io.connect('http://localhost');
socket.on('news', function(data){
console.log(data);
socket.emit('my other event', {my: 'data'});
});

</script>

</body>
</html>


Thanks for your help !

Answer Source

Change

app.listen(3000);

to

server.listen(3000);

Your socket.io is attached to the http server server. See line: var io = require('socket.io')(server); and Not the express server app.

So obviously socket.io couldn't serve anything, as the server it expected never started listening.

TESTED! THIS ANSWER WAS SUCCESSFULLY REPLICATED IN MY LOCAL ENVIRONMENT!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download