neryushi
neryushi

Reputation: 128

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

I am making a website that accesses the devices sensors and sends them via socket.io to my local machine. I can't access the device sensors without HTTPS, so I have to use HTTPS for the website, which is why I uploaded my site to Heroku. The problem is the localhost server I open on my computer is HTTP, and my HTTPS website can't send data from HTTPS (heroku site) to HTTP (local machine: localhost). Is there any way I can share the data between them?

This is the code used to connect to localhost written on the heroku client side site:

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

While this is what I use in my local machine:

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

});

as per socket.io documentation

I get this error:

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.

Upvotes: 0

Views: 2654

Answers (2)

divillysausages
divillysausages

Reputation: 8033

Like @R3FL3CT says, it's most likely a CORS issue - check your console to be sure.

It seems that the initial request that it makes is the one getting blocked. For example,

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

Would get blocked with the error

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.

Whereas just using a pure WebSocket

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

Connected okay.

So your solution is to either roll back to an earlier version of socket.io that doesn't force cors (before v3), or just use your own WebSocket - example: https://www.websocket.org/echo.html

Upvotes: 1

R3FL3CT
R3FL3CT

Reputation: 586

Here's one way you could do something to try and communicate. If you host your own version of CORS Anywhere, you can communicate with http:// websites. I have a working link you can use, if you don't want to have to host one, but here the Github is. The way it works, is that you append the URL to the end of your URL for CORS Anywhere.

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

Upvotes: 0

Related Questions