【问题标题】:Using require('cors') but still getting CORS error使用 require('cors') 但仍然出现 CORS 错误
【发布时间】:2021-09-21 04:08:42
【问题描述】:

我正在尝试构建一个简单的 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"]
    }
  });

但这给出了同样的错误。

【问题讨论】:

    标签: node.js reactjs socket.io cors


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      仔细检查您的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
      };
      

      【讨论】:

      • 我使用app.use(cors(corsOptions)) 添加了这些选项,但得到了同样的错误。这是将这些选项传递给 cors 的正确方法吗?
      • @sigil,我刚刚更新了我的答案,我正在使用 Typescript,所以我更正为 javascript
      猜你喜欢
      • 2017-04-29
      • 2019-11-29
      • 2020-06-22
      • 2016-03-21
      • 2019-04-16
      • 2021-03-01
      • 2020-01-01
      • 2020-01-28
      • 2017-08-04
      相关资源
      最近更新 更多