localtunnel 和 CORS 无法正常工作

localtunnel and CORS not working properly

我正在使用 localtunnel 公开我的后端和前端。现在,我有一个非常简单的设置,如下所示:

const httpServer = require('http').createServer();
const socketIO = require('socket.io');

const io = socketIO(httpServer, { cors: { origin: '*' } });

io.on('connection', (socket) => {
  ...
});

httpServer.listen(5000, () => {
  console.log(`Listening on the port 5000`);
});

然后我使用带有 lt --port 5000 的 localtunnel 公开这个后端。然后我得到 URL,在我的 React 前端中设置它,在端口 3000 上启动前端应用程序 运行,然后 lt --port 3000。然后,当我尝试连接到后端时,我不断收到此错误。

Access to XMLHttpRequest at 'https://tame-mayfly-63.loca.lt/socket.io/?EIO=4&transport=polling&t=NbU6WbU' from origin 'https://spotty-robin-42.loca.lt' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

首先我认为这是 localtunnel 的一些错误,但后来尝试使用 ngrok 并且错误是相同的。我正在启用来自 CORS 的所有来源,所以我不知道会发生什么。

curl "https://tame-mayfly-63.loca.lt/socket.io/?EIO=4&transport=polling" 有效,但我想那是因为在使用 cURL 发出请求时忽略了 CORS。

我找到了解决问题的方法。看起来您首先需要访问为您的后端提供服务的动态 url,然后单击“继续”。如此一来,CORS就不是问题了