Socket.io/React/Express - getting "connect_error due to server error"

Viewed 26

I'm trying to use Socket.io in my React.js + Express project, but I can't seem to connect my socket properly. When I run the server code on its own, it seems to be all right (maybe because I'm not trying to connect a socket?). However, running the whole project produces "connect_error due to server error". There are polling requests similar to "http://localhost:5000/socket.io/?EIO=4&transport=polling&t=O7eK6kF" that are made periodically; these all have status 200 but still fail to connect.

I've tried the suggestions in several other Stack Overflow questions (server- and client-side socket.io versions are ok, different options on client-side initialization don't work), but they haven't worked so far.

My (abridged) server code is

const http = require("http");
const express = require("express");
const session = require("express-session");

// get environment variables
require("dotenv").config();

// create a new express server
const app = express();
app.use(express.json());

// set up a session
app.use(
    session({
        secret: process.env.SESSION_SECRET,
        resave: false,
        saveUninitialized: false,
        genid: function(req) { return uuid.v4(); },
    })
);
app.get("*", (req, res) => {
    res.sendFile(path.join(reactPath, "index.html"));
});

// any server errors cause this function to run
app.use((err, req, res, next) => {
    const status = err.status || 500;
    res.status(status);
    res.send({
        status: status,
        message: err.message,
    });
});

// server
const server = http.Server(app);
server.listen(process.env.PORT || 3000, () => {
    console.log("Server running");
});

// socket
const io = require("socket.io");
const socket = io(server);
socket.on("connection", (socket) => {
    console.log(`socket has connected ${socket.id}`);
});

while my client-side socket code is

import { connect } from "socket.io-client";
const endpoint = window.location.hostname + ":" + window.location.port;
export const socket = connect(endpoint, { rejectUnauthorized: false });

socket.on("connect", () => {
  console.log("connected");
});
socket.on("connect_error", function (err) {
  console.log("connect_error", err);
});

Ideas on how to fix this?

0 Answers
Related