0
votes

I am trying to set up a chat application using react and express with socket.io but I got this error when trying to connect the client side with the server using socket.io (I am using Firefox and I got the same error on all other browsers)

Firefox cannot connect to the server at ws://localhost:5000/socket.io/?EIO=4&transport=websocket.

The connection to ws://localhost:5000/socket.io/?EIO=4&transport=websocket was interrupted while the page was loading.

Here is my code :

Client side:

import React, {useState, useEffect} from 'react';
import queryString from 'query-string';
import io from "socket.io-client";


var connectionOptions =  {
  "force new connection" : true,
  "reconnectionAttempts": "Infinity", 
  "timeout" : 10000,                  
  "transports" : ["websocket"]
};

let socket;

const Chat = ({ location }) => {
    const [name, setName] = useState('');
    const [room, setRoom] = useState('');
    const [message, setMessage] = useState('');
    const [messages, setMessages] = useState([]);
    const ENDPOINT = 'http://localhost:5000/';


    useEffect(() => {
        const{name , room} = queryString.parse(location.search);

        socket = io.connect(ENDPOINT, connectionOptions);
        
        setName(name);
        setRoom(room);

        
        socket.emit('receve', {name, room}, (error) => {

          if(error) alert(error);
         
        });

        return () => {
            socket.emit('disconnect');
            socket.off();
        }

    }, [ENDPOINT, location.search]);
    
    useEffect(() => {
      socket.on('message', (message) => {
        setMessage([...messages, message]);
      })
    }, [messages]);

    const sendMessage = (e) => {
      e.preventDefault();

      if(message) {

        socket.emit('sendMessage', message, () => setMessage(''));
      }
    }

    console.log(message, messages);

    return (
      <div className="outerContaienr">
        <div className="container">
          <input 
          value={message} 
          onChange={(e) => setMessage(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' ? sendMessage(e) 'enter code here': null}  
          />
        </div>
      </div>
        
    )

}

export default Chat;

server side :

 const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const cors = require('cors');
const {addUsers, RemoveUser, getUser, getUsersInRoom} = require('./users.js')

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

const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server);

app.use(cors());
app.use(router);

  io.on("connect_error", (err) => {
    console.log(`connect_error due to ${err.message}`);
  });

io.on('connect', socket => {
  socket.on('receve', ({ name, room }, callback) => {
    const { error, user } = addUsers({ id: socket.id, name, room });
       //console.log(user);
       if (error)
         return callback(error);

       socket.emit('message', { user: 'admin', text: `${user.name}, welcome to the room ${user.room}` });
       socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name}, has joined!` });

       socket.join(user.room);

       callback();
     });

  socket.on('sendMessage', (message, callback) => {
    const user = getUser(socket.id);

    io.to(user.room).emit('message', { user: user.name, text: message});

    callback();

  });
    socket.on('disconnect', () => {
        console.log('User had left');
    })
});


server.listen(PORT);

Thanks in advance

1
may be upgrading your firefox version can do the job for you. There's a bug in firefox, please note.user4782805

1 Answers

0
votes

I think you need to add the CORS in the following format. Try this snippet:

const io = socketio(server,{
  cors: {
    origin: "*",
  },
});

Hope that fixes the situation, on mine machine (Chrome), that solved the nasty error.