无法通过局域网将套接字客户端(reactjs)连接到套接字服务器(express)(同一网络上的不同机器)

Unable to connect socket client (reactjs) to socket server (express) over lan network (different machine on same network)

我有两台不同的机器连接到同一个网络。

我想通过 LAN 网络连接使用 LAN 分配的 IP 地址下面是简单的演示

套接字客户端(Reactjs,IP:192.168.0.103)到套接字服务器(Express,IP:192.168.0.114)

问题: 获取错误:访问被 CORS 阻止(尝试了 express 'cors' 中间件但失败,没有解决方案)

这是工作正常的简单 React 代码

import socketClient from 'socket.io-client';
const SocketServer = 'http://192.168.0.114:3000';

function App() {

  var socket = socketClient(SocketServer, {secure: true});

  socket.emit('client_connected', { payload: {
    message: "react client is connected"
  }});

  return (
    <div>
      
    </div>
  );
}

export default App;

和简单的快递代码(也可以正常工作)

const cors = require('cors')
const express = require('express')
const bodyParser = require('body-parser')

const app  = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server)


app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static('public'))

app.use(cors({
    origin: '*'
}));

app.set('view engine', 'ejs')

app.get('/', (req,res) => {

    res.sendFile(__dirname + '/index.html')
})

io.on('connection', (socket) => {
    socket.on('client_connected', (message) => {
        console.log(message)
    })
})

server.listen(3000, () => {
  console.log('listening on *:3000');
});

在 ReatJs 的浏览器控制台中获取屏幕截图时出错

enter image description here

我尝试在 express 中设置 headers 但遇到同样的错误

任何帮助将不胜感激

你需要在socket server not express中配置cors

查看此处以了解有关配置的更多信息https://socket.io/docs/v3/handling-cors/

配置示例

const io = require("socket.io")(httpServer, {
  cors: {
    origin: "https://example.com",
    methods: ["GET", "POST"]
  }
});