53

i keep on getting the error /socket.io/socket.io.js 404 (Not Found) Uncaught ReferenceError: io is not defined

my code is

var express = require('express'), http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

server.listen(3000);

and

<script src="/socket.io/socket.io.js"></script>

what is the problem ???

any help is welcome!

16
  • Are you serving your HTML files from the same Node app as well? Commented Oct 17, 2013 at 12:36
  • possible duplicate of Socket.io not being served by Node.js server Commented Oct 17, 2013 at 12:38
  • @robertklep: ah no, i have an index.html page... From the app.js I get info: socket.io started Commented Oct 17, 2013 at 12:38
  • @Bondye nope, that's not the issue here Commented Oct 17, 2013 at 12:40
  • 2
    @hausinho if your HTML is being served by a different server you need to include the full URL to the socket.io file: <script src="http://localhost:3000/socket.io/socket.io.js"></script> (or some other hostname, obviously) Commented Oct 17, 2013 at 12:41

11 Answers 11

85

Copying socket.io.js to a public folder (something as resources/js/socket.io.js) is not the proper way to do it.

If Socket.io server listens properly to your HTTP server, it will automatically serve the client file to via http://localhost:<port>/socket.io/socket.io.js, you don't need to find it or copy in a publicly accessible folder as resources/js/socket.io.js & serve it manually.

Code sample
Express 3.x - Express 3 requires that you instantiate a http.Server to attach socket.io to first

var express = require('express')
  , http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

//... 

server.listen(8000);

Happy Coding :)

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

6 Comments

This should be the validated answer for this socket.io issue. Thanks!
I had similar problem which was related to the fact that I was refactoring old code, which was using app.listen(3000);. This was not working. When I've changed it to server.listen(3000); it starts working fine.
I'd suggest that the index.html which calls ' var socket = io('localhost);' is also updated to use the correct port
ah! You inject the server into the listen method. Thanks!
@edufinn gosh. You nailed it man, the problem was exactly that. Thank you
|
13

How to find socket.io.js for client side

install socket.io

npm install socket.io

find socket.io client

find ./ | grep client | grep socket.io.js

result:

./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js

copy socket.io.js to your resources:

cp ./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js /home/proyects/example/resources/js/

in your html:

<script type="text/javascript" src="resources/js/socket.io.js"></script>

4 Comments

ok copied the socket.io.js into a folder which i called js so now its <script src="js/socket.io.js"></script> - but now i get the error localhost:3000/socket.io/1/?t=1382087281918 !?!?!?
this is not the error, this is the connection request, you must create the events in your server/client to comunicate with
+1, searched for some hours before I finally found this source that there is a socket.io.js that may be copied into the lib
This is useful solution when using just client without server
9

It seems that this question may have never been answered (although it may be too late for the OP, I'll answer it for anyone who comes across it in the future and needs to solve the problem).

Instead of doing npm install socket.io you have to do npm install socket.io --save so the socket.io module gets installed in your web development folder (run this command at the base location/where your index.html or index.php is). This installs socket.io to the area in which the command is run, not globally, and, in addition, it automatically corrects/updates your package.json file so node.js knows that it is there.

Then change your source path from '/socket.io/socket.io.js' to 'http://' + location.hostname + ':3000/socket.io/socket.io.js'.

Comments

3

... "You might be wondering where the /socket.io/socket.io.js file comes from, since we neither add it and nor does it exist on the filesystem. This is part of the magic done by io.listen on the server. It creates a handler on the server to serve the socket.io.js script file."

from the book Socket.IO Real-time Web Application Development, page 56

1 Comment

This is not enought to answer the question.
1

You must just follow https://socket.io/get-started/chat/ and all will work.

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function(){
  console.log('listening on *:3000');
});

Comments

1

If you are following the socket.io tutorial https://socket.io/get-started/chat/, you should add this line as below.

app.use(express.static(path.join(__dirname, '/')))

This is because in the tutorial, Express will only catch the url / and send the file of index.html.

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

However, in the index.html, you have a script tag (<script src="/socket.io/socket.io.js"></script>) requests the resouce of socket.io-client, which is not routed in index.js (it can be found in console-network that the url is http://localhost:3000/socket.io/socket.io.js).

Comments

1

Please check the directory path mentioned in your code.By default it is res.sendFile(__dirname + '/index.html');

make sure you index.html in proper directory

Comments

1

Steps to debug

  1. npm install socket.io --save in static files (index.html) for example, you may have installed it globally and when you look at the debugger, the file path is empty.

  2. Change your script file and instantiate the socket explicitly adding your localhost that you have set up in your server file

     <script src="http://localhost:5000/socket.io/socket.io.js"></script>
         <script>
           const socket = io.connect("localhost:5000");
            $(() =>
    

    Double check that the data is flowing by opening a new browser tab and pasting http://localhost:5000/socket.io/socket.io.js you should see the socket.io.js data

  3. Double check that your server has been set-up correctly and if you get a CORs error npm install cors then add it to the server.js (or index.js whatever you have chosen to name your server file)

     const cors = require("cors");
     const http = require("http").Server(app);
     const io = require("socket.io")(http);
    

    Then use the Express middleware app.use() method to instantiate cors. Place the middleware this above your connection to your static root file

     app.use(cors());
     app.use(express.static(__dirname));
    
  4. As a final check make sure your server is connected with the http.listen() method where you are assigning your port, the first arg is your port number, for example I have used 5000 here.

     const server = http.listen(5000, () => {
       console.log("your-app listening on port", server.address().port);
     });
    
  5. As your io.on() method is working, and your sockets data is connected client-side, add your io.emit() method with the callback logic you need and in the front-end JavaScript files use the socket.on() method again with the call back logic you require. Check that the data is flowing.

I have also edited a comment above as it was the most useful to me - but I had some additional steps to take to make the client-server connection work.

Comments

1

If you want to manually download "socket.io/socket.io.js" file and attaché to html (and not want to get from server runtime) you can use https://cdnjs.com/libraries/socket.io

like

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>

Comments

0

while this doesn't have anything to do with the OP, if you're running across this issue while maintaining someone else's code, you might find that the problem is caused by the coder setting io.set('resource', '/api/socket.io'); in the application script, in which case your HTML code would be <script>type="text/javascript" src="/api/socket.io/socket.io.js"></script>.

Comments

0

If this comes during development. Then one of the reasons could be you are running a client-side file(index.html). But what you should do is run your server(example at localhost:3000) and let the server handle that static file(index.html). In this way, the socket.io package will automatically make
<script src="/socket.io/socket.io.js"></script> available on the client side.

Illustration(FileName: index.js):

const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const port = 3001 || process.env.PORT;
const app = express();
const server = http.createServer(app);
const io = socketio(server);

//MiddleWares
app.use(express.json());
app.use(
  express.urlencoded({
    extended: false,
  })
);
app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
  res.sendFile('index.html');
});

io.on('connect', (socket) => {
console.log('New user joined');
}
server.listen(port, () => {
  console.log(`App has been started at port ${port}`);
});

After this run your server file by the command node index.js Then open the localhost:${port}, Replace port with given in the index.js file and run it.

It solved my problem. Hope it solves yours too.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.