Otávio Augusto
Otávio Augusto

Reputation: 37

React and Express - Error during WebSocket handshake on localhost

I'm having trouble setting up a WebSocket connection using socket.io on my localhost. I'm using express on the server side and React on the client side.

I get the following message whenever I try to open a connection:

WebSocket connection to 'ws://localhost:5000/socket.io/?EIO=4&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 404

I've seen some people having similar issues related to nginx or other web servers, but my problem is happening on localhost, which is why I am asking this question

Server-side code (I am using modules for the import, and I would like to keep it that way)

import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { createServer } from 'http';
import * as socketio from 'socket.io';

const app = express();
app.use(bodyParser.json({ limit: '30mb', extended: true }));
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }));
app.use(cors());
app.use('/foo', bar);

const server = createServer(app)
const io = new socketio.Server(server);

io.on('connect', socket => {...});

const PORT = process.env.PORT || 5000
app.listen(PORT, () => console.log(`Server running on port ${PORT}`)))

Client-side code (I've already tried passing different values to the "transports" array but it did not help) :

import io from 'socket.io-client';

let socket;
const Component = () => {
    ...

    const { id } = useParams();
    const ENDPOINT = 'ws://localhost:5000';

    useEffect(() => {
        socket = io(ENDPOINT, { transports: ['websocket', 'polling', 'flashsocket'] });

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

    }, [ENDPOINT, id]);

    return (...)
})

Upvotes: 0

Views: 338

Answers (1)

ZealousWeb
ZealousWeb

Reputation: 1751

Change last line of Server side code to

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Upvotes: 1

Related Questions