score:1

runned you example and it looks like client connection is rejected because of the cors policy.

you can get this fixed by adding this to your server:

const io = require('socket.io')(http, {
  cors: {
    origin: "http://localhost:3000"
  }
});

above assumes that you are running reactjs server in port 3000. if you are using different port then you need to change this to match.

you can also set cors to "*". this means that all origins are accepted. but please keep in mind that this is considered a bad practice.

const io = require('socket.io')(http, {
  cors: {
    origin: "*"
  }
});

about cors

cors is a security mechanism in the browser. when browser takes connection to some other server than the host of the website, the browser will block the response by default.

in your case you are running your website on one origin (for example localhost:3000) and socket io server in localhost:4000. these are considered to be different origins by the browser.

way to fix this is that the server will send cors-header with the response. that will inform the browser that this connection is ok to use "cross origin". the snippet above will just add cors header to the socket io's initial response.

you can see these headers in the chrome developer tools on the network tab. you will also get a cors error in the console if the connection is blocked.

enter image description here

working ok for me

just copied your updated code and it is working fine for me. added cat background for bonus.

enter image description here


Related Query

More Query from same tag