Error GET /socket.io/socket.io.js net::ERR_ABORTED 404 - node.js

I can't solve this error of socket.io it shows in the console
GET /socket.io/socket.io.js net::ERR_ABORTED 404
Refused to execute script from '/socket.io/socket.io.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Uncaught ReferenceError: io is not defined
at script.js:1:14
I made this with node.js
The files are below (main server file is index.js)
index.js
var express = require("express");
var app = express();
var http = require("http");
var server = http.createServer(app);
var { Server } = require("socket.io");
var io = new Server(server);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/style.css", (req, res) => {
res.sendFile(__dirname + "/style.css");
});
app.get("/script.js", (req, res) => {
res.sendFile(__dirname + "/script.js");
});
io.on("connection", (socket) => {
socket.on("chat message", (msg) => {
io.emit("chat message", msg);
});
});
app.listen(3000);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test Socket.io</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<h1>Test</h1>
</center>
<script src="/socket.io/socket.io.js"></script>
<script src="script.js"></script>
</body>
</html>
style.css
body {
font-family: Arial;
}
script.js
var socket = io();
Help will be appreciated.

Replace this:
app.listen(3000);
with this:
server.listen(3000);
app.listen() creates a new server so the server you're starting is NOT the server that socket.io is hooked to, therefore the socket.io library is not hooked up to that server and when the request for /socket.io/socket.io.js comes in, you don't get the socket.io JS library.
Here's the code for app.listen():
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
You can see that it creates a new server and then calls .listen() on that new server.
Your express code works because app is hooked to the server created by app.listen(), but socket.io is hooked to the server created by:
var server = http.createServer(app);
var io = new Server(server);
which is never started and is not running. So, socket.io is never hooked up to the server that is actually running. Instead, you should just create and start one server and hook both app and socket.io to that one server.

Related

nodejs socket.io not working on localnetwork

I'm trying to implement a chat on my website but I can't make socket.io work on my localnetwork (it works for localhost but I cant access it from another machine).
Server code:
const path = require('path');
const host = '0.0.0.0';
const port = 3000;
const express = require('express');
const app = express();
const cors = require('cors');
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const script = require('./script');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.listen(port, host, function() {
console.log('Running at: ',host,port);
});
app.use(express.static('public'));
app.use(express.json({limit:'1mb'}));
client code:
const socket = io();
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Proflands!</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="client.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body> </body>
</html>
Error i'm getting:
Failed to load resource: the server responded with a status of 404 (Not Found) socket.io.js:1
where I got my code from: https://socket.io/get-started/chat
It works if I use "http://localhost:3000" but I want it to work on whole localnetwork.
as #Lawrence Cherone commented:
changing:
app.listen(port, host, function() {
console.log('Running at: ',host,port);
});
to:
http.listen(port, host, function() {
console.log('Running at: ',host,port);
});
solved the problem.
If you getting the error: 404 (Not Found) socket.io.js: Then the issue is the src path to the socket.io client in:
<script src="/socket.io/socket.io.js"></script>
If you accessing the server from other machines/websites etc, then change that path to an absolute URL to get the client. Otherwise, it is trying to access the socket.io server relatively, being the same server the client is on.
<script src="http://myserver:3000/socket.io/socket.io.js"></script>

Code was correctly but show Error on node js socket io?

Code was correctly but show Error on node js socket io ?
....................................................................................................................
app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req,res){
res.sendfile('index.html');
});
var clients = 0;
io.on('connect', function(socket){
clients++;
io.sockets.emit('boardcast', {message: clients + ' clients connected!'});
//console.log(io.sockets)
socket.on('disconnect', function(){
clients--;
io.sockets.emit('boardcast', {message: clients + ' clients connected!'});
});
});
http.listen(3000, function(){
console.log('start server on port :3000');
});
index.html
<html>
<head></head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script type="text/javascript">
var socket = io();
socket.on('boardcast', function(data){
document.body.innerHTML = '';
document.write(data.message);
});
</script>
<h1>hello world</h1>
</body>
</html>
.
ssh
node app.js
return value
start server on port :3000
express deprecated res.sendfile: Use res.sendFile instead app.js:6:6
Putting the commands from your question into an answer.
Express are depracating res.sendfile in favour of res.sendFile.
sendFile needs the full path to the file.
Assuming that index.html is in the same folder as app.js you can use:
const path = require('path');
res.sendFile(path.join(__dirname, 'index.html'))
If you move files around in the future simple tweak path.join

Can’t connect to node.js server on client side

I’m having a problem getting started with Node.js.
I’ve created a basic server that I know works, because if I navigate to http://localhost:5000 in my browser I get the expected message. However, I’m having trouble then connecting to this server on the client side with a basic HTML page.
My Node.js app looks like this:
var http = require('http');
var socket = require('socket.io');
var port = process.env.PORT || 5000;
var players;
var app = http.createServer(function(request, response) {
response.write('Server listening to port: ' + port);
response.end();
}).listen(port);
var io = socket.listen(app);
function init() {
io.configure(function() {
io.set('transports', [ 'xhr-polling' ]);
io.set('polling duration', 10);
});
io.sockets.on('connection', onSocketConnection);
};
function onSocketConnection(client) {
console.log('New connection');
console.log(client);
};
init();
My HTML page looks like this (based on https://github.com/mongolab/tractorpush-server/blob/master/index.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.on('all', function(data) {
console.log(data);
});
socket.on('complex', function(data) {
console.log(data);
});
</script>
</body>
</html>
I understand that the sockets.io.js file is automatically generated by socket.io, but I just get the following error when I view my index.html file:
Uncaught ReferenceError: io is not defined
How do I actually connect to my server?

cannot get client server running using express in node.js

hey i just started tinkering with node.js and am a complete noob. i am trying to get a simple client server communication going using socket.io and express (i have never used these before).
here is my code for the app(app.js):
var sys = require('sys'),
express = require('express'),
app = express('localhost');
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
var socket = require('socket.io').listen(server);
socket.on('connection', function (client){
// new client is here!
setTimeout(function () {
client.send('Waited two seconds!');
}, 2000);
client.on('message', function () {
}) ;
client.on('disconnect', function () {
});
});
and here is my code for the client(client.html):
<html>
<p id="text">socket.io</p>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = new io.Socket(),
text = $('#text');
socket.connect();
socket.on('connect', function () {
text.html('connected');
});
socket.on('message', function (msg) {
text.html(msg);
});
socket.on('disconnect', function () {
text.html('disconnected');
});
});
</script>
i got most of the code from:
NodeJS + socket.io: simple Client/Server example not working
and the changed it to be compatible with express 3.x
however when i run the server and open my client using chrome it tells me that it is unable
to load resource file:///socket.io/socket.io.js
i have already installed express and socket.io using npm
also i have read through atleast 20 similar posts and have not been able to find an answer
please help me. thank you
socket.io.js file needs to be served from port 3000, like localhost:3000.
So here is what you do change
<script src="/socket.io/socket.io.js"></script> to
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
Are you opening the client.html page directly from the local file system? The request for socket.io.js should look like http://localhost/socket.io/socket.io.js not file:///socket.io/socket.io.js.

Why does the following nodejs code not work with socketio+express 3?

I dont get why this does not work:
I have a sample.js containing:
var http = require('http');
var socket = require('socket.io');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
io.sockets.on('connection', function(client) {
console.log('Client Connected...');
client.emit('messages', {hello: 'world'});
});
server.listen(8080);
I have an index.html page that contains:
<!DOCTYPE html>
<html>
<head>
<script src="socket.io.js"></script>
<script>
var server = io.connect('http://mydomain:8080');
server.on('messages', function(data) {
alert(data.hello);
});
</script>
</head>
<body>
</body>
</html>
Update: When using the socket.io-client.js library, when I go to the http://mydomain:8080 page, I get an "info - unhandled socket.io url"
Can someone point out what I may be doing wrong?
Your server's never sending out index.html because you never told it to. You need something like:
app.get('/', function(req, res) {
res.sendfile('index.html');
});
assuming index.html is at the root level of your app, or, more generally:
app.use(express.static(__DIRNAME+'/public'));
and then put index.html (along with any other static files like stylesheets) in the public subdirectory of your app.

Resources