javascript CORS拒绝连接到套接字io

l7mqbcuq  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(141)

我尝试使用socket io来实时发送和接收数据,但是当我运行server并打开使用socket. io-client连接的客户端页面时,我收到了一个错误
我安装了cors,并像以前那样多次使用它,我试图设置我的响应的头部,以允许从不同的来源访问,但没有工作。
这是我得到的错误:

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

这是我的服务器端代码

require("dotenv").config();

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require("cors");

const { Server } = require("socket.io");
const app = express();
const server = require("http").Server(app);
const io = new Server(server);

app.use(bodyParser.json());
app.use(
  cors({
    origin: "*",
  })
);

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
});

io.on("connection", (socket) => {
  console.log("a user connected");
});

const port = process.env.PORT || 5000;
const url = process.env.MONGO_URI;

const start = async () => {
  try {
    await connectDB(url);
    server.listen(port, (req, res) => {
      console.log(`Server is listening on port ${port}`);
    });
  } catch (error) {
    console.log(error);
  }
};

start();

我在前端所做的就是使用socket.io-client库连接到react应用程序中的服务器,就像这样。

import io from "socket.io-client";

const socket = io("http://localhost:5000");

任何帮助都很感激

jq6vz3qz

jq6vz3qz1#

您需要将cors选项传递给io Server构造函数本身。
例如,代替

const io = new Server(server);

你需要

const io = new Server(server, {
  cors: {
    origin: '*',
  }
});

相关问题