【问题标题】:localtunnel and CORS not working properlylocaltunnel 和 CORS 无法正常工作
【发布时间】:2021-08-02 08:59:12
【问题描述】:

我正在使用 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。

【问题讨论】:

    标签: node.js express socket.io cors localtunnel


    【解决方案1】:

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

    【讨论】:

    • 正如页面上所说,如果存在特定于浏览器的标头,它将继续阻止这些标头,直到您指定标头以允许请求。这里的页面是指:来自本地隧道的托管页面,用于他们生成的 url。
    猜你喜欢
    • 2017-04-06
    • 2015-09-16
    • 2017-05-05
    • 1970-01-01
    • 2018-08-02
    • 2019-05-12
    • 2021-07-24
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多