如何将 socket.io websocket 从 WSS 降级到 WS?

How to downgrade socket.io websocket to WS from WSS?

我正在制作一个访问设备传感器的网站,并通过 socket.io 将它们发送到我的本地机器。 如果没有 HTTPS,我无法访问设备传感器,所以我必须为该网站使用 HTTPS,这就是我将我的网站上传到 Heroku 的原因。问题是我在我的电脑上打开的localhost服务器是HTTP,而我的HTTPS网站无法将数据从HTTPS(heroku站点)发送到HTTP(本地机器:localhost)。有什么办法可以在他们之间共享数据吗?

这是在 heroku 客户端站点上用于连接到本地主机的代码:

const socket = io("https://192.168.1.15:16", { transports: ['websocket', 'polling', 'flashsocket']});

虽然这是我在本地机器上使用的:

const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpsServer,{

});

根据socket.io documentation

我收到这个错误:

Mixed Content: The page at '**The website**' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://192.168.1.35:16/socket.io/?EIO=4&transport=websocket'. This request has been blocked; this endpoint must be available over WSS.

这是您尝试交流的一种方式。如果您托管自己的 CORS Anywhere 版本,则可以与 http:// 个网站进行通信。我有一个工作 link you can use, if you don't want to have to host one, but here the Github 是。它的工作方式是将 URL 附加到 URL 的末尾,以便在任何地方使用 CORS。

e.g https://cors.anywhere.com/google.com

如@R3FL3CT 所说,这很可能是 CORS 问题 - 检查您的控制台以确定。

它发出的初始请求似乎被阻止了。例如,

const socket = io('wss://echo.websocket.org/');
socket.on("connection", (socket) => {
    console.log(`Connected!`)
});

会因错误而被阻止

Access to XMLHttpRequest at 'https://echo.websocket.org/socket.io/?EIO=4&transport=polling&t=Nb17pKo' from origin 'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

而仅使用纯 WebSocket

const websocket = new WebSocket('wss://echo.websocket.org/');
websocket.onopen = e => {
    console.log(`Connected!`);
}

连接正常。

因此您的解决方案是回滚到不强制 cors(v3 之前)的早期版本 socket.io,或者只使用您自己的 WebSocket - 例如:https://www.websocket.org/echo.html