socket.io 的 CORS 问题

CORS issue with socket.io

我的网站需要一个 websocket,我想使用 socket.io

但是,我遇到了 CORS 问题:

Access to XMLHttpRequest at 'http://localhost:2021/socket.io/?EIO=4&transport=polling&t=NlbFGS2' from origin 'http://localhost:63341' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
polling-xhr.js:202 

GET http://localhost:2021/socket.io/?EIO=4&transport=polling&t=NlbFGS2 net::ERR_FAILED

所以我在 socket.io 网站上找到了这段代码,但我仍然遇到同样的问题...

const app = require('express')();
const http = require('http').createServer(app);
const io = require("socket.io")(http, {
    cors: {
        origin: ["http://localhost:63341/"],
        methods: ["GET", "POST"]
    }
})

这是客户端的代码:

<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.1.2/dist/socket.io.msgpack.min.js"></script>
<script>
    let socket = io('http://localhost:2021')
</script>

在您的 backend 服务器上执行以下步骤:

  1. 运行 npm install cors

  2. 创建后添加此代码app:

    app.use(cors({
        origin: "http://localhost:63341"
    }))
    
  3. 重新启动服务器并检查它是否工作。

  4. 如果还是不行,那就把你的line 3改成这样:

    const io = require("socket.io")(http); // no cors configuration.
    

你可以使用它来允许任何东西连接......但是不要在生产中这样做。

export const io = new Server(http, {
  cors: { origin: "*" },
});