socket.io 与 react socket.io-client 通信时重新加载后无法连接

socket.io wont connect after reload when communicating with react socket.io-client

我正在尝试创建简单的 socket.io server/client

当我向服务器发送 http 请求时出现此错误

首先我创建了 html 文件作为客户端,一切正常

当我开始在我的 React 应用服务器中使用 Socket 时,我疯了!

我第一次启动服务器时一切正常,套接字工作正常 但是当我刷新页面时,我无法再从任何地方连接到服务器

服务器代码...

const express = require('express');
class Server {
    constructor({ config, router, logger }) {
    this.config = config;
    this.logger = logger;
    this.express = express();

    this.express.disable('x-powered-by');
    this.express.use(router);
  }

  startSocket(server) {
    console.log('initing');
    const io = require('socket.io')(server, {
      cors: {
        origin: '*',
        methods: ['GET', 'POST'],
      },
    });
    io.on('connection', (socket) => {
      console.log('connected ' + socket.id);
    });
  }

  start() {
    return new Promise((resolve) => {
      const http = this.express.listen(this.config.web.port || 6066, () => {
        const { port } = http.address();
        this.logger.info(`[p ${process.pid}] Listening at port ${port}`);
        resolve();
      });
      this.startSocket(http);
    });
  }
}

module.exports = Server;

反应代码

import { io } from 'socket.io-client';
export class Socket {
  constructor() {
    this.socket = io('http://localhost:4000', {
      rejectUnauthorized: false,
    });
    this.binds();
  }

  binds() {
    this.socket.on('connect', () => {
      console.log(this.socket.id);
    });
    this.socket.on('bong', (msg) => {
      console.log(msg);
    });
  }
  bing() {
    this.socket.emit('bing', { msg: 'test' });
  }
}
export default new Socket();

原来 'socket.io' 与 'express-status-monitor' 冲突导致了这个问题