Guy Arilei
Guy Arilei

Reputation: 37

React- can't connect to server socket

I build a server & client. the client is trying to connect to the server by socket however I'm getting the following error in the console :

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NS2s-Z_' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The server:

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

const PORT =  process.env.PORT || 5000;


const router = require('./router');

const app = express();
const server = http.createServer(app);
const io = socketio(server);

io.on('connection',(socket) =>{
    console.log('[Server] We have new connection !!!');
    socket.on('disconnect',()=>{
        console.log('[Server] WeUser has left !!!')
    });
});

app.use(router); 

server.listen(PORT,()=>{
    console.log(`[Server] has started listen on port ${PORT}`);
});

The client:

let socket;
const Chat= ({location}) =>{
    const ENDPOINT ='localhost:5000';
    const [name,setName] = useState('');
    const [room,setRoom] = useState('');
    useEffect(()=>{
        const {name,room} = queryString.parse(location.search) // get url
        socket = io(ENDPOINT);
        //Update state with new name and room
        setName(name);
        setRoom(room);
        console.log(socket);
        // socket.emit('ERROR');
    },[ENDPOINT,location.search]);
    return (<h1>Chat</h1>);
}

At first, I was sure the problem was that the server isn't on the same port as the client request. But sadly it's not the case.

Edit: I've changed both ports to be 3000 and it seems to work, however, with any other port it's not. Is there a way the client cant send ack to connection because of os permission

Upvotes: 0

Views: 3101

Answers (2)

Fl&#225;vio Zanoni
Fl&#225;vio Zanoni

Reputation: 46

I had the same problem, you can try adding the transport on the client side, worked for me

const socket = io("localhost:5000", { transports: ["websocket"] });

Upvotes: 3

codemonkey
codemonkey

Reputation: 7915

Your express needs to enable CORS. Here is how. Install this package:

npm i cors

require it:

const cors = require('cors');

Then right below your const app = express();, paste this:

app.use(cors());

Upvotes: 0

Related Questions