Socket.io 没有连接到我的 Express.js 服务器

Socket.io is not connecting to my Express.js server

我正在尝试让 Socket.io 连接到我的 Express.js 服务器,但尽管密切关注 Socket.io 网站上给出的示例,但我仍无法成功连接它们和我一直用来参考的其他代码。

当我在客户端尝试 socket.on('connect', console.log(socket.connected)) 时,它总是 returns false 而当我记录 connect_error 时,它总是 returns server error具有以下回溯:

Error: server error
    at Socket.onPacket (socket.js:317:1)
    at XHR.push../node_modules/@socket.io/component-emitter/index.js.Emitter.emit (index.js:143:1)
    at XHR.onPacket (transport.js:100:1)
    at callback (polling.js:83:1)
    at Array.forEach (<anonymous>)
    at XHR.onData (polling.js:86:1)
    at Request.push../node_modules/@socket.io/component-emitter/index.js.Emitter.emit (index.js:143:1)
    at Request.onData (polling-xhr.js:188:1)
    at Request.onLoad (polling-xhr.js:229:1)
    at XMLHttpRequest.xhr.onreadystatechange (polling-xhr.js:147:1)

这些是我在后端的 index.js 服务器文件的相关部分:

const express = require('express');
const cors = require('cors');
const app = express();
// /db/session is express-session related code
const session = require('./db/session');
const { createServer } = require('http');
const { Server } = require('socket.io');
const PORT = process.env.PORT || 5000;

const httpServer = createServer(app);

app.use(cors({
    // DEV_ORIGIN is http://localhost:3000
    origin: process.env.DEV_ORIGIN,
    credentials: true,
}));

const io = new Server(httpServer, {
    cors: {
        origin: process.env.DEV_ORIGIN,
        methods: ["GET", "POST"],
        credentials: true
    }
});

app.use(session);

io.use((socket, next) => {
    session(socket.request, {}, next);
});

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

// this never seems to do anything
io.on('connection', function() {
    console.log('Connected')
});

这是我在客户端的 Socket.io 连接的主要文件:

import io from 'socket.io-client';

// API_ORIGIN is http://localhost:5000
export let socket = io(process.env.API_ORIGIN, {
    withCredentials: true,
    autoConnect: true,
});

我正在这样的组件中使用此文件中的 socket 进行测试:

import { socket } from '../../services/socket.js';
import React, { useEffect } from 'react';

export default function Lobby() {

    useEffect(() => {
        socket.on('connect',
            console.log(socket.connected)
        )
        socket.on('connect_error', (err) => {
            console.log(err)
        });
    }, [])

}

但正如我上面提到的,socket.connected 总是 returns false。非常感谢您的帮助!

我设法解决了。该问题是由 process.env.API_ORIGIN 引起的。通过如下更改代码,我能够让它工作。

新客户端socket.io文件:

import { io } from "socket.io-client";
import { serverAddress } from "../settings";

export let socket = io(serverAddress, {
    withCredentials: true,
    autoConnect: true,
});

以及我创建的设置文件:

const LOCAL_ADDRESS = 'http://localhost:5000';
const PRODUCTION_ADDRESS = [PRODUCTION URL HERE]
export const devEnv = process.env.REACT_APP_ENV === 'development';
export const serverAddress = devEnv? LOCAL_ADDRESS : PRODUCTION_ADDRESS;