【问题标题】:How can i make React JS and Socket IO connect together via Express JS server?如何通过 Express JS 服务器使 React JS 和 Socket IO 连接在一起?
【发布时间】:2021-06-05 12:18:33
【问题描述】:

所以我最近正在尝试使用 socket io,但它不允许我连接到 React JS。在 console.log 它给了我一些奇怪的错误信息。看看下面的代码。我将发布 React 和 localhost 的图像。

服务器(Express JS):

const app = require("express")();
const bodyParser = require("body-parser");
const cors = require("cors");
const http = require("http").createServer(app);
const io = require("socket.io")(http);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
io.on("connect", (socket) => {console.log("connected");});
app.listen(5000, () => console.log(`Running on port...`));

【问题讨论】:

  • 嘿,你解决了这个问题吗?

标签: javascript node.js reactjs express sockets


【解决方案1】:

您需要添加一个 GET 请求可以到达的虚拟路由。

试试这个:

const express = require("express");
const app = express();
const router = express.Router();
const bodyParser = require("body-parser");
const cors = require("cors");
const http = require("http").createServer(app);
const io = require("socket.io")(http);

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

router.get("/", (req, res) => {
  res.send({ response: "I am alive" }).status(200);
});

app.use("/socket.io", router);

io.on("connect", (socket) => {
  console.log("connected");
});

app.listen(5000, () => console.log(`Running on port...`));

【讨论】:

    【解决方案2】:

    您可以在 useEffect 挂钩中初始化套接字,或者使用 io.connect(URL) 而不是 io(URL) 后端看起来不错。我写了一篇关于它的博客article

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 2017-08-07
    • 2019-04-10
    • 2019-10-28
    • 2019-07-07
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多