【问题标题】:Socket.io application works locally but not on HerokuSocket.io 应用程序在本地工作,但在 Heroku 上不工作
【发布时间】:2021-03-05 01:54:25
【问题描述】:

我正在创建一个 React 应用程序和一个 Node 服务器,它们应该使用 socket.io 通过套接字相互通信。当我在本地计算机上连接了所有东西时,我不会遇到任何问题。但是,当我使用部署的服务器时,我的 React 应用程序在控制台中收到以下错误:

Access to XMLHttpRequest at 'https://{URL TO MY HEROKU SERVER}/socket.io/?EIO=4&transport=polling&t=NNjgExO' 
from origin '{URL FOR MY HEROKU REACT APP}' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
The 'Access-Control-Allow-Origin' header contains the invalid value '48506'.

在将应用程序放在一起时,我在本地遇到了类似的问题,并了解到我需要在我的服务器中使用 cors 来允许连接。当我在本地机器上这样做时,它起作用了。但是,既然我已经部署了它,我又遇到了这种类型的错误。我知道我需要更改某种 cors 设置,但我真的不知道需要更改什么。
这是服务器代码:

const server = http.createServer(app);
const io = socketio(server, {
  cors: {
    allRoutes: true,
    origin: PORT,
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true,
  },
});

这是用于连接的 React 应用代码:

socket = io(ENDPOINT, {
      withCredentials: true,
      extraHeaders: {
        "my-custom-header": "abcd",
      },
    });

EDNPOINT 指的是我的本地主机服务器或已部署服务器的 url,具体取决于我工作的环境。任何帮助将不胜感激!

【问题讨论】:

    标签: node.js reactjs heroku socket.io


    【解决方案1】:

    我设法通过反复试验找出了 cors 设置。对于任何感兴趣的人,以下是适合我的设置:

    服务器:

    const cors = require("cors");
    const socketio = require("socket.io");
    
    const app = express();
    app.use(cors());
    
    const server = http.createServer(app);
    
    const io = socketio(server, {
      cors: {
        origin: "*",
        methods: ["GET", "POST"],
        allowedHeaders: ["content-type"],
      },
    });
    

    客户:

    socket = io(ENDPOINT);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      相关资源
      最近更新 更多