我有一个服务器代码,看起来如下:
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>
当我访问web http://localhost:3001时,我得到控制台日志,套接字。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什么都没有被记录在屏幕上,什么可能可能的问题?
在看了我的react-app后,我意识到问题是cors
。所以我在服务器上设置了cors
,一切都工作了:
const server: S = createServer(app);
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
....