localtunnel 和 CORS 无法正常工作

dar*_*izp 2 node.js cors express socket.io localtunnel

我正在使用 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`);
});

Run Code Online (Sandbox Code Playgroud)

然后我用 localtunnel 公开这个后端lt --port 5000。然后,我获取 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.
Run Code Online (Sandbox Code Playgroud)

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

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

dar*_*izp 8

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