Triyugi Narayan Mani
Triyugi Narayan Mani

Reputation: 3109

404 not found when using socket.io-client with react

I am implementing socket.io-client package in my react app. My react app is using express and webpack. When using following code:

import io from 'socket.io-client';

const socket = io('http://localhost');

in any component, I am getting following error:

polling-xhr.js:264 POST http://localhost/socket.io/?EIO=3&transport=polling&t=Lrprs_y 404 (Not Found)

Same error is coming when using http://localhost:80.

And when using 127.0.0.1 at the place of 'localhost`, its throwing following error:

XMLHttpRequest cannot load http://127.0.0.1/socket.io/?EIO=3&transport=polling&t=Lrq3G9W. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

Upvotes: 1

Views: 3023

Answers (1)

V. Lipunov
V. Lipunov

Reputation: 1252

I think all you need to do is put your code into componentDidMount. Do something like this:

// Client
componentDidMount() {
    const socket = io('http://localhost:8000');
    socket.on('message', message => {
      console.log(message);
    });
}

// Server
const io = require('socket.io')();

io.on('connection', (client) => {
   console.log('a user connected:', client);
});
io.listen(8000);
console.log('socket io is listening on port ', 8000);
setInterval(() => {
  io.send('hello world');
}, 1000);

Then run npm run build and npm run prod (or whatever your command is to start the node js server). P.S. you can also use express with socket io

Upvotes: 1

Related Questions