使用 require('cors') 但仍然出现 CORS 错误

Using require('cors') but still getting CORS error

我正在尝试构建一个简单的 React/Node/Socket.io 应用程序。

这是 React app.js:

import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:4001";

function App() {
  const [response, setResponse] = useState("");

  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.on("FromAPI", data => {
      setResponse(data);
    });
  }, []);

  return (
    <p>
      It's <time dateTime={response}>{response}</time>
    </p>
  );
}

export default App;

这里是节点 app.js:

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const cors = require('cors');

const port = process.env.PORT || 4001;
const index = require("./routes/index");

const app = express();
//app.use(cors());
app.use(cors({
    origin: ['http://localhost:3000'],
    credentials: true
}));
app.use(index);

const server = http.createServer(app);
const io = socketIo(server);

let interval;

io.on("connection", (socket) => {
  console.log("New client connected");
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => getApiAndEmit(socket), 1000);
  socket.on("disconnect", () => {
    console.log("Client disconnected");
    clearInterval(interval);
  });
});

const getApiAndEmit = socket => {
  const response = new Date();
  // Emitting a new message. Will be consumed by the client
  socket.emit("FromAPI", response);
};

server.listen(port, () => console.log(`Listening on port ${port}`));

当我加载 localhost:3000 并检查 JavaScript 控制台时,我收到此错误:

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

require('cors')app.use(cors()) 不应该解决这个问题吗?我都试过了

app.use(cors())

app.use(cors({
        origin: ['http://localhost:3000'],
        credentials: true
    }));

但无论如何得到了相同的结果。

编辑:根据 Socket.io 文档 here,我试过这个:

const socketIo = require("socket.io",{
    cors: {
      origin: "http://localhost:3000",
      methods: ["GET", "POST"]
    }
  });

但是这给出了同样的错误。

仔细检查您的 allowedHeaders 并允许 methods,工作示例:

const corsOptions = {
    allowedHeaders: ['X-ACCESS_TOKEN', 'Access-Control-Allow-Origin', 'Authorization', 'Origin', 'x-requested-with', 'Content-Type', 'Content-Range', 'Content-Disposition', 'Content-Description'],
    credentials: true,
    methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
    origin: ['http://macog.local:5001','http://localhost:5001', 'https://app.foo.com', 'http://10.0.2.2:5001'],
    preflightContinue: false
};

将 CORS 参数传递给 socketIO 构造函数解决了问题,如下所示:

const io = socketIo(server,{
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
    credentials:true
  }
});