Fastify & Socket.io CORS 不被接受

Posted

技术标签:

【中文标题】Fastify & Socket.io CORS 不被接受【英文标题】:Fastify & Socket.io CORS not accepted 【发布时间】: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 */ ) 【参考方案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"],
  ,
);

【讨论】:

以上是关于Fastify & Socket.io CORS 不被接受的主要内容,如果未能解决你的问题,请参考以下文章

socket.io/?EIO=3&transport=polling&t=1345678 不充电

Socket.io & Redis - 适合 io 游戏的架构?

socket.io 广播功能 & Redis pub/sub 架构

设置 React 组件以监听 socket.io

Phaser.js 中的 Node.js 和 Socket.io 未连接 socket.io/?EIO=3&transport=polling

Nodejs & Socket.io 可以支持多少用户?