简体   繁体   English

Fastify & Socket.io CORS 不被接受

[英]Fastify & Socket.io CORS not accepted

I'm tring to set up fastify-socket.io, fastify-cors, but I'm still getting CORS errors.我正在尝试设置 fastify-socket.io、fastify-cors,但我仍然遇到 CORS 错误。

I have fastify-cors and fastsity-socket.io registered我已经注册了 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).

Here is the back-end code:这是后端代码:

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);
    });
  });
});

Here is the front end code:这是前端代码:

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;

I'm not sure why I'm getting these cors Errors I think it has something to do with fastify-socket.io我不确定为什么会收到这些 cors 错误,我认为这与fastify-socket.io

Found the solution, it doesn't seem that registering fastifyCors before fastifyIO makes a difference, but I changed that anyway.找到了解决方案,在 fastifyIO 之前注册 fastifyCors 似乎没有什么不同,但我还是改变了。 I wasn't configuring fastifyIO correctly.我没有正确配置 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"],
  },
});

With Fastify cli scaffold使用 Fastify cli 脚手架

fastify.register(require('./plugins/cors.js'))
fastify.register(require('./plugins/socketio.js'), {
    // put your options here
})
fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'plugins'),
    options: Object.assign({}, opts),
    ignorePattern: /.*(socketio|cors).js/
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM