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>
Related
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.
I include following socket js file in my html to communicate on the server
<script src="/socket.io/socket.io.js"></script>
and i write my connection code in user.js file
var socket = io();
socket.on('connect',()=>
{
console.log('connected to the server');
});
socket.on('disconnect',()=>
{
console.log('disconnected to the server');
});
and i include it in my html page using
<script type="text/javascript" src="../routes/users.js"></script>
but it said GET http://localhost:3000/routes/users.js faild
You will have to serve static files from node to get access to it.
There are many libraries that do the same, Express is most used.
In express you can do it like,
const express = require('express');
const http = require('http');
const app = express();
app.use(express.static(path.join(__dirname, '../routes')));
var server = http.createServer(app);
server.listen(3000, () => console.log(`API running on localhost: ` + 3000));
above use of static, will give access to every file that is in routes folder.
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"'
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.
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.