Express 服务器未连接到 NodeJS 抛出错误函数

问题描述 投票:0回答:1
import React, { useState, useRef, useEffect } from 'react'
import user from '../components/Client';
import Editor from '../components/Editor';
import { initSocket } from '../socket';
import ACTIONS from '../action';
import { useLocation, useNavigate, Navigate, useParams } from 'react-router-dom'
const Compiler = () => {
    const socketRef = useRef(null);
    const location = useLocation();
    const reactNavigator = useNavigate();
    const { roomId } = useParams();

    useEffect(() => {
        const init = async () => {
            socketRef.current = await initSocket();
            socketRef.current.on('connect_error', (err) => handleErrors(err));
            socketRef.current.on('connect_failed', (err) => handleErrors(err));

            function handleErrors(e) {
                console.log('socket error', e);
                alert("Socket connection failed")
            }
            socketRef.current.emit(ACTIONS.JOIN, {
                roomId,
                username: location.state?.username,
            });
        };
        init();
    }, []);
    const [clients, setClients] = useState([
        { socketId: 1, username: 'aman' },
        { socketId: 2, username: 'am2an' },
    ])
    if (!location.state) {
        return < Navigate to="/" />;
    }
    return <div className='mainblock'>
        <div className='sidebar'>
            <div className='innersidebar'>
                <div className='logo'>
                    <img src='/logo1.png' alt='logo' className='logoimg' />
                </div>
                <h3>Connected</h3>
                <div className='clientsList'>
                    {
                        clients.map((client) => (
                            <client key={client.socketId} username={client.username} />
                        ))
                    }
                </div>
            </div>
            <button className='btn copybtn'>Copy Room ID</button>
            <button className='btn leavebtn'>Leave</button>
        </div>
        <div className='editorblock'>
            <Editor />
        </div>
    </div>
};

export default Compiler;

这是用户登陆并加入服务器的编译器登陆页面

这里我们接受用户名和roomid

const express = require('express');
const app = express();
const http = require('http');
const { Server } = require('socket.io');
const ACTIONS = require('./src/action');
const server = http.createServer(app);
const io = new Server(server);

const userSocketMap = {};
function getallConnectedClients(roomId) {
    return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map((socketId) => {
        return {
            socketId,
            username: userSocketMap[socketId],
        };
    })
}
io.on('connection', (socket) => {
    console.log('socket connected', socket.id);
    socket.on(ACTIONS.JOIN, ({ roomId, username }) => {
        userSocketMap[socket.id] = username;
        socket.join(roomId);
        const clients = getallConnectedClients(roomId);
    })
})




const PORT = process.env.PORT || 5000
server.listen(PORT, () => console.log(`Listening on port ${PORT}`));

这是服务器代码,不知道出了什么问题

这里是警报

谁能帮我解决这个问题

我尝试重置整个服务器,检查了所有使用的参数,但这里似乎没有任何作用

node.js reactjs express socket.io ejs
1个回答
0
投票

从 Socket.IO v3 开始,您需要显式启用跨源资源共享(CORS)。

在您的后端,执行以下操作:

const io = new Server(server, {
    cors: {
        origin: 'http://localhost:3000',
        methods: ['GET','POST'],
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.