Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET/ socket io not found 404

Im following the socket io documentation though still am getting an error

polling-xhr.js:157 GET http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NtNlWd6 404 (Not Found)

it my be something very simple though I am stuck

below is my code

server.js

const express = require('express'); //Line 1
const app = express(); //Line 2
const port = process.env.PORT || 5000; //Line 3


const http = require('http').Server(app);

const io = require('socket.io')(http);



//Whenever someone connects this gets executed
io.on('connection', function(socket) {
    console.log('A user connected');
 
    //Whenever someone disconnects this piece of code executed
    socket.on('disconnect', function () {
       console.log('A user disconnected');
    });
 });



// This displays message that the server is running and listening to specified port
app.listen(port, () => console.log(`Listening on port ${port}`)); //Line 6

// create a GET route
app.get('/express_backend', (req, res) => { //Line 9
    console.log("printing from the server f3f134g")
  res.send({ express: "YOUR EXPRESS BACKEND IS CONNECTED TO REACT" }); //Line 10
}); //Line 11

index.html



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1"
    />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link
      rel="apple-touch-icon"
      href="%PUBLIC_URL%/logo192.png"
    />
   
  </head>
  <body>
    
    <script src="https://cdn.socket.io/4.4.0/socket.io.min.js" integrity="sha384-1fOn6VtTq3PWwfsOrk45LnYcGosJwzMHv+Xh/Jx5303FVOXzEnw0EpLv30mtjmlj" crossorigin="anonymous"></script>
    
<script>
  var socket = io();
</script>

    <div id="root"></div>
  
  </body>
</html>

please note both

```<script src="/socket.io/socket.io.js"></script>```

and

    <script src="https://cdn.socket.io/4.4.0/socket.io.min.js" integrity="sha384-1fOn6VtTq3PWwfsOrk45LnYcGosJwzMHv+Xh/Jx5303FVOXzEnw0EpLv30mtjmlj" crossorigin="anonymous"></script>

give an error

like image 214
benpalmer Avatar asked Jan 19 '26 19:01

benpalmer


1 Answers

The problem is in your server code.

You bind socket.io to http, but only app listens on the port (5000). You need to make http listen on that port.

Change this line:

app.listen(port, () => console.log(`Listening on port ${port}`));

to

http.listen(port, () => console.log(`Listening on port ${port}`));
like image 190
tromgy Avatar answered Jan 22 '26 14:01

tromgy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!