【问题标题】:Socket.io-Client: React+TypeScript: Socket.io-client not listening from the serverSocket.io-Client:React+TypeScript:Socket.io-client 没有从服务器监听
【发布时间】:2021-11-10 20:31:03
【问题描述】:

我有一个如下所示的服务器代码:

import express, { Response } from "express";
import { Server, Socket } from "socket.io";
import { createServer, Server as S } from "http";
// import router from "./routes";

// ----
const app: express.Application = express();
// app.use(router);

app.get("/", (_req: any, res: Response) =>
  res.status(200).sendFile(__dirname + "/index.html")
);
const PORT: any = 3001 || process.env.PORT;
const server: S = createServer(app);
const io = new Server(server, {});

io.on("connection", (socket: Socket) => {
  console.log("we have a new connection");
  console.log(socket.id);
});
//
server.listen(PORT, () => {
  console.log(`The server is running on port: ${PORT}`);
});

在我的index.html 这是我的代码:

<script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
    </script>

当我在 http://localhost:3001 访问网络时,我得到控制台日志,socket.io 正在侦听新连接。我想要的是使用socket.io-client 和在端口 3000 上运行的反应服务器。这是我尝试过的:

import io from "socket.io-client";
const client = io("http://localhost:3001/").connect();
const App: React.FC<{}> = () => {
  return (
    <div className="app">
      <h1>Socket.io</h1>
    </div>
  );
};

当我访问 http://localhost:3000 时,屏幕上没有任何记录,可能是什么问题?

【问题讨论】:

    标签: node.js reactjs sockets socket.io


    【解决方案1】:

    在查看了我的 react-app 之后,我意识到问题出在 cors 上。所以我在服务器上设置了cors,一切正常:

    const server: S = createServer(app);
    const io = new Server(server, {
      cors: {
        origin: "*",
        methods: ["GET", "POST"],
      },
    });
    ....
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 1970-01-01
      • 2021-02-28
      • 2018-03-14
      • 2018-05-13
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多