node.js /socket.io/socket.io.js not found

Javascriptnode.jssocket.io

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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 :)

Solution 2 - Javascript

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>

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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');
});

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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>

Solution 10 - Javascript

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

Solution 11 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhausinhoView Question on Stackoverflow
Solution 1 - JavascriptAmol M KulkarniView Answer on Stackoverflow
Solution 2 - JavascriptZiTALView Answer on Stackoverflow
Solution 3 - JavascriptBlubberguy22View Answer on Stackoverflow
Solution 4 - JavascriptJordan GeorgiadisView Answer on Stackoverflow
Solution 5 - JavascriptTomas KukisView Answer on Stackoverflow
Solution 6 - JavascriptAlexanderZhaoView Answer on Stackoverflow
Solution 7 - JavascriptSudarshan GaikwadView Answer on Stackoverflow
Solution 8 - JavascriptSumiView Answer on Stackoverflow
Solution 9 - JavascriptAbhijeet JagdaleView Answer on Stackoverflow
Solution 10 - Javascriptjcomeau_ictxView Answer on Stackoverflow
Solution 11 - JavascriptNaman KalraView Answer on Stackoverflow