Fastify & Socket.io CORS 不被接受

Fastify & Socket.io CORS not accepted

我正在尝试设置 fastify-socket.io、fastify-cors,但我仍然遇到 CORS 错误。

我注册了 fastify-cors 和 fastsity-socket.io

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NoUUJ6g. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

后台代码如下:

import fastify from "fastify";
import fastifyIO from "fastify-socket.io";
import fastifyCors from "fastify-cors";

const server = fastify();''
const PORT = 5000;

server.register(fastifyIO);
server.register(fastifyCors),
  {
    origin: "*",
    methods: "GET,POST,PUT,PATCH,DELETE",
  };

server.listen(PORT, () => {
  console.log(`Server running on port:${PORT}`);
});

server.get("/", (request, reply) => {
  reply.status(200).send({ ServerOnline: true });
});

server.ready().then(() => {
  server.io.on("connection", (socket) => {
    console.log("user connected" + socket.id);
    socket.on("message", (data) => {
      console.log(data);
    });
  });
});

前端代码如下:

import "./App.css";
import { io } from "socket.io-client";

function App() {
  const sendData = () => {
    const socket = io("http://localhost:5000");
    socket.on("connection");
    const sendMessage = () => {
      socket.emit("message", "hey it worked!");
    };
    sendMessage();
  };

  return (
    <div className="app-container">
      <h1>Socket.IO</h1>
      <button onClick={sendData}>Send</button>
    </div>
  );
}

export default App;

我不确定为什么会收到这些 cors 错误,我认为这与 fastify-socket.io

有关

找到解决办法了,在fastifyIO之前注册fastifyCors似乎没有什么区别,但我还是改了。我没有正确配置 fastifyIO。

server.register(fastifyCors, {
  origin: "*",
  methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
});
server.register(fastifyIO, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
  },
});