benpalmer
benpalmer

Reputation: 393

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

Upvotes: 15

Views: 51254

Answers (7)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

const express = require("express");
var app = express();
var server = require("http").Server(app);
const io = require("socket.io")(server);
const port = 3000;

io.on("connection", (socket) => {
  console.log(socket.id);
  

  socket.on("connect", () => {
    console.log("a user connected");
    console.log(socket.connected); // true
  });

  socket.on("connect_error", () => {
    console.log("user connect_error");
  });

  socket.on("disconnect", () => {
    console.log(socket.connected); // false
    console.log("user disconnected");
  });

  socket.on("chat message", (msg) => {
    console.log("message: " + msg);
    io.emit("chat message", msg);
  });

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

Upvotes: 0

Ganesh Dammuluri
Ganesh Dammuluri

Reputation: 21

Update and make http listen on that port and update your code as below.

http.listen(port, () => console.log(`Listening on port ${port}`)); //Line 6

Upvotes: 0

zam zyn
zam zyn

Reputation: 81

my issue was i was running the port using app.listen in and used const server=http.createserver(app) and was using this server for socket.io.The problem was solved when i changed app.listen to server.listen.i will post my working code below

const express = require("express");
const app = express();
const cors = require("cors");
const createError = require("http-errors");
const userRouter = require("./router/user");
const adminRouter = require("./router/admin");
const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");
const morgan = require("morgan");
const session = require("express-session");
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
app.use(morgan("dev"));

app.use(
  cors({
    origin: ["http://localhost:3000", "http://localhost:3001"],
    credentials: true,
  })
);

const io = new Server(server, {
  cors: {
    origin: 'http://localhost:3000',
    methods:['GET','POST']
  }
})

app.use(
  session({
    secret: "mySecretKey",
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: 24 * 60 * 60 * 1000,
    },
  })
);

app.use(cookieParser());
require("dotenv").config();
mongoose
  .connect(process.env.DATABASE, {
    dbName: "hotelova",
    useNewUrlParser: true,
  })
  .then(() => {
    console.log("Db connected");
  })
  .catch((err) => {
    console.log(err);
  });

io.on("connection", (socket) => {
  console.log("a user connected");
  socket.on("disconnect", () => {
    console.log("user disconnected");
  });
});

app.use("/users", userRouter);

app.use("/admin", adminRouter);

server.listen(4000, () => {
  console.log("server running");
});

app.use((req, res, next) => {
  next(createError(404));
});

app.use((err, req, res, next) => {
  console.log(err);`enter code here`
  res.sendStatus(500);
});

Upvotes: 8

Titurex
Titurex

Reputation: 81

This ended up working for me server Side:

const express = require("express");
const app = express();
const httpServer = require('http').createServer(app);

// socket.io and then i added cors for cross origin to localhost only
const io = require('socket.io')(httpServer, {
       cors: {
        origin: "http://localhost:3000", //specific origin you want to give access to,
    },
});

// watch collection from db
const db = mongoose.connection;
db.once('open', () => {
    console.log('Connected to MongoDB database');
    const collection = db.collection('comments');
    const changeStream = collection.watch();
    changeStream.on('change', (change) => {
        console.log(change);
        io.emit('change', change);
    });
});


For the client side

//install and import socket.io-client
import io from 'socket.io-client';
const socket = io('http://localhost:5000');


//use your data how you please
useEffect(() => {
    socket.on('change', (change) => {
      setData([...data, change]);
    });
  }, [data]);
  
  console.log(data)

Upvotes: 1

Md Shayon
Md Shayon

Reputation: 375

I have tried searching for the result in many forms but I get failed. After doing some research for a few days I found my solution.

  1. Do not run your node js and socket io server on the same port on the production. Instead, use two different port
const express  = require("express");
const { Server } = require("socket.io");

const app = express();
const io = new Server(httpsServer, { /* options */ });

app.listen(8000, ()=> console.log("server is running on 8000"));
io.listen(9000);
  1. Make sure your firewall does not block the port you are running on your socket server. (If you are doing reverse proxy using nginx or apache2 you do not need to open any random port)
sudo ufw status
sudo ufw allow 8000
sudo ufw allow 9000
  1. If you are using nginx for reverse proxy in your node js server you could deny all of your open prots
sudo ufw status
sudo ufw deny 8000
sudo ufw deny 9000
  1. Make some reverse proxy if you are using nginx or apache for node js and socket io
server {



    root /var/www/pastewetween.com;

    index index.html index.htm index.nginx-debian.html;
    server_name pastebetween.com; # managed by Certbot
    return 301 https://$server_name$request_uri;


    location / {
        # First attempt to serve request as file, then
        return 301 https://$server_name$request_uri;
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;

    }
    location /socket.io {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;

      proxy_pass http://localhost:9000;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }
    location /r{
        proxy_pass http://localhost:8000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

Upvotes: 1

S_i_l_e_n_t C_o_d_e_r
S_i_l_e_n_t C_o_d_e_r

Reputation: 363

You can try this also

  //?as app.listen returns a server we can use for socket.io
 const serverWithSocket = app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`);
     
     });
     const io = require('socket.io')(serverWithSocket); //? invoking the func also something like func()
      
      io.on('connection', (socket) => {
        console.log('a user connected');
        socket.on('disconnect', function () {
          console.log('A user disconnected');
        });
      });

Upvotes: 0

tromgy
tromgy

Reputation: 5823

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}`));

Upvotes: 44

Related Questions