【问题标题】:Fastify & Socket.io CORS not acceptedFastify & Socket.io CORS 不被接受
【发布时间】:2021-12-07 18:30:53
【问题描述】:

我正在尝试设置 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有关

【问题讨论】:

  • 尝试注册fastifyCors 之前 fastifyIO。此外,您对register() 的使用看起来不正确。应该是server.register(fastifyCors, { /* options here */ })

标签: javascript socket.io cors rest fastify


【解决方案1】:

找到了解决方案,在 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"],
  },
});

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 2021-05-03
    • 2016-12-19
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多