Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

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

Writer Emily Wong

i keep on getting the error / 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="/"></script>

what is the problem ???

any help is welcome!

16

11 Answers

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

6

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/

copy socket.io.js to your resources:

cp ./node_modules/ /home/proyects/example/resources/js/

in your html:

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

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 '/ to ' + location.hostname + ':3000/.

... "You might be wondering where the / 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

You must just follow 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');
});

If you are following the socket.io tutorial , 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="/"></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 ).

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

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=""></script> <script> const socket = io.connect("localhost:5000"); $(() =>

    Double check that the data is flowing by opening a new browser tab and pasting 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.

If you want to manually download "" file and attaché to html (and not want to get from server runtime) you can use

like

<script src="" integrity="sha512-eVL5Lb9al9FzgR63gDs1MxcDS2wFu3loYAgjIH0+Hg38tCS8Ag62dwKyH+wzDb+QauDpEZjXbMn11blw8cbTJQ==" crossorigin="anonymous"></script>

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

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="/"></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 commandnode index.jsThen 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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy