0

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.

thefabdev
  • 753
  • 1
  • 7
  • 20

2 Answers2

1

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.

-1

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>
Samuel Goldenbaum
  • 18,391
  • 17
  • 66
  • 104
  • Same error with that line – José Gabriel Nov 26 '19 at 14:43
  • Thats because you have not specified the protocol above. Update it to the correct URL format ``````or use the cdn `````` The error 404 with the filename is clearly explaining that it cannot locate the script to load: `404 (Not Found) socket.io.js:1` – Samuel Goldenbaum Nov 26 '19 at 15:03