NodeJs express.use disturbs the socket.io reference - node.js

I am new to NodeJS and socket.io. I just intend to detect a socket connected to the Express server. It was working fine for me when I was not using Express server.
Then for some reason I used Express and wanted everything to be static so I added this line to the Server File.
app.use(express.static(__dirname));
The above line disturbs my client.html file. Below is the code for my client.html. I debugged it using developer console and found that the script src containing "/socket.io/socket.io.js" is not valid.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="/socket.io/socket.io.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/css/style.css"/>
<title>Untitled Document</title>
<script>
var socket = io.connect();
socket.on('connect',function(){
console.log("socket.io working");
});
</script>
</head>
</html>
What concept or thing am I missing?
For more info: This is my directory structure of the application.
-MyChatRoom
--ChatServer.js
--html
----client.html
--css
----style.css
--images
--node_modules
----socket.io
----express
Edited
For better understanding here is my ChatServer.js code
fs = require('fs');
url = require('url');
express = require('express');
app = express();
server = require('http').createServer(app);
socketio = require('socket.io')(server);
//The root and all subs are made static
app.use(express.static(__dirname));
app.get('/',function(request,response){
response.sendFile(__dirname + "/html/index.html");
});
app.listen(3000);
var connectedUsers = 0;
socketio.on('connection',function(socket){
connectedUsers++;
console.log('client connected');
});

app.listen(3000);
should be
server.listen(3000);
You need to listen on the http module not the express one.
Express is passed through the http module when you instantiate it. Socket.io uses the http module, this is why you need to listen on this to get it to work.

Related

socket.io send data from server to client

I am trying to send some json object from the server side to the client side.
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function(json) {
io.send('message', json);
});
app.listen(3000);
and on index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data) {
console.log(data);
});
</script>
</body>
</html>
I keep getting this error
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?
EIO=2&transport=polling&t=1602487581123-0' from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Use "socket.io": "^2.3.0", for server side, change server side code to following:
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function() {
io.send('message', json);
});
http.listen(3000, () => console.log('HTTP server is listening on port 3000'));
For the CORS header, any origins being allowed by default.
And I recommend you use the latest version of socket.io for the client-side. You can use this CDN.
client side:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js" integrity="sha512-AcZyhRP/tbAEsXCCGlziPun5iFvcSUpEz2jKkx0blkYKbxU81F+iq8FURwPn1sYFeksJ+sDDrI5XujsqSobWdQ==" crossorigin="anonymous"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data, json) {
console.log(data, json);
});
</script>
</body>
</html>
Create HTTP Server for client-side:
☁ 64313396 [master] ⚡ http-server -p 3001
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:3001
http://172.31.160.227:3001
http://10.23.128.81:3001
The output of browser console:

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>

Show continuous connection message in nodejs socket.io

I am trying to develop a live chat application using laravel. I face a problem. When I run "node index.js" , 'A connection has made' message has shown continuously in command prompt.
my index.js file is:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
app.get('/', function(request, response){
response.sendFile(__dirname+ '/index.html');
});
io.on('connection', function(socket){
console.log('A connection has made');
// socket.on('chat.message', function(message){
// io.emit('chat.message', message);
// });
});
My index.html page is:
<!DOCTYPE html>
<html>
<head>
<title>Live Chat</title>
</head>
<body>
<div class="container" id="chat">
<h1> Chat System </h1>
</div>
<script type="text/javascript">
var socket = io();
</script>
</body>
</html>
How can I solve it?
The usual reason that your client is continually trying to connect over and over again is because you have a mismatched client and server version of socket.io making them incompatible. You don't show how you load the socket.io Javascript in your web page, but if you do it like this:
<script src="/socket.io/socket.io.js"></script>
Then, you will always get the version that exactly matches your server from your server automatically (this is a route that the socket.io server automatically adds to your Express server).
If you are loading socket.io from a CDN, then you have to either switch to the above to load it from your own server or manually specify the exact same version from the CDN as you are running on the server.
If you are using it on React/NextJs
just declare these as global
import socketClient from "socket.io-client";
const SERVER = "http://127.0.0.1:8000";
const socket = socketClient(SERVER);
export default chatApplication=()=>{
//main component
}
Change port number from 3000 to 7000 for example.

The server has not found anything matching the requested URI node

I have below folder structure in VS2015:
The server.js has below code:
var express = require('express')
var app = express();
var http = require('http').Server(app);
var path = require('path');
var port = process.env.port || 1337;
app.use(express.static(__dirname + 'client'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,'client', 'HTML1.html'));
});
http.listen(port, function () {
console.log(`listning on ${port}`);
})
and Html1.Html has below code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head data-ng-app="imageLoaderApp">
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
</div>
<script src="/client/scripts/angular.js"></script>
<script type="text/javascript">
var app = angular.module('imageLoaderApp', []);
app.controller('loadController', function ($scope) {
console.log(`i'm here.'`);
});
</script>
</body>
</html>
When I'm hitting below url in browser
http://localhost:1337/
I'm getting below error in console:
This is happening with all the js files. I even tried to move the html and js files in main folder still getting the same error.
What am I doing wrong?
It looks like HTML1.html is in the client folder. If that is the case I think you need to put the path to the js relative to it so: 'src="scripts/angular.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