简体   繁体   English

使用 socket.io 连接 React 前端和 Express 后端

[英]connecting react frontend and express backend using socket.io

I have one frontend made in React, running on port 3000 and one express/node server running on port 5000, both of them on the same computer (no.network used).我有一个用 React 制作的前端,运行在端口 3000 上,还有一个 express/node 服务器运行在端口 5000 上,它们都在同一台计算机上(没有使用网络)。

I try to make them communicate using socket.io for the backend and socket.io-client for the frontend.我尝试让他们在后端使用 socket.io 并在前端使用 socket.io-client 进行通信。

The connexion works somehow, but I have some error message in the frontend console, namely:该连接以某种方式工作,但我在前端控制台中收到一些错误消息,即:

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=OMmsufE' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
polling.js:334          

GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=OMmsufE net::ERR_FAILED 200

here's the front end code, App.js:这是前端代码,App.js:

import './App.css';

function App() {
  const socket = require('socket.io-client')('http://localhost:5000/socket.io/');

  socket.on('connect', () => {
    console.log('Connected to server');

    socket.on('message', (message) => {
      console.log('Received message:', message);
    });

    socket.emit('message', 'Hello, server!');
  });

socket.on('disconnect', () => {
  console.log('Disconnected from server');
});

  return (
    <div className="App">App 
    </div>
  );
}

and the backend index.js:和后端 index.js:

const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);

const cors = require("cors")
app.use(cors({ origin: 'http://localhost:3000' }));
io.on('connection', (socket) => {
  console.log('User connected');

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });

  socket.on('message', (message) => {
    console.log('Received message:', message);
    io.emit('message', message);
  });
});
app.use("/socket.io/", (req, res, next) => {
  next()
})

app.get("/", (req, res) => console.log("hello"))

app.use(cors())

server.listen(5000, () => {
  console.log('Server listening on port 5000');
});

Anyone having an idea?有人有想法吗?

so, indeed, as Konrad said, the problem came from the frontend, and especially this line:所以,确实,正如康拉德所说,问题来自前端,尤其是这一行:

const socket = require('socket.io-client')('http://localhost:5000/socket.io');

which was necessary to turn into, as Konrad said:正如康拉德所说,有必要变成:

const socket = require('socket.io-client')('http://localhost:5000/);

but also, it was necessary to add:而且,有必要补充:

const socket = require('socket.io-client')('http://localhost:5000/', {transports: ['websocket'], upgrade: false});

and now it works现在它起作用了

I'm pretty sure that your socket.io endpoint is blocking the true endpoint我很确定您的socket.io端点正在阻止真正的端点

Client:客户:

// remove `socket.io` here
const socket = require('socket.io-client')('http://localhost:5000/');

Server:服务器:

const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);

const cors = require("cors")
app.use(cors({ origin: 'http://localhost:3000' }));
io.on('connection', (socket) => {
  console.log('User connected');

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });

  socket.on('message', (message) => {
    console.log('Received message:', message);
    io.emit('message', message);
  });
});

app.get("/", (req, res) => console.log("hello"))

app.use(cors())

server.listen(5000, () => {
  console.log('Server listening on port 5000');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM