javascript mqtt websocket在localhost中工作良好,在https服务器中不工作



javascript mqtt websocket连接在localhost中运行良好,而不是在https服务器中工作

代码

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hello MQTT World</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="paho-mqtt.js"></script>
</head>
<body>
<script>
var client = new Paho.Client('myserver.com',8083,'asdfg');
client.connect({
reconnect:true,
onSuccess:function(){
console.log('Connected');
client.subscribe("/abcd/+/#");  // Where 16 is the bspid
}
});
client.onMessageArrived=function(message){
console.log(message);
};
</script>

<ul id="logger"></ul>

</body>
</html>

Fehlermeldung

> Error paho-mqtt.js:1054 Mixed Content: The page at
> 'https://myserver.com/pis/monitoring/mqtt.html' was loaded over HTTPS,
> but attempted to connect to the insecure WebSocket endpoint
> 'ws://myserver.com:8083/mqtt'. This request has been blocked; this
> endpoint must be available over WSS.
> LibraryFactory.ClientImpl._doConnect @ paho-mqtt.js:1054
> LibraryFactory.ClientImpl.connect @ paho-mqtt.js:887 Client.connect @
> paho-mqtt.js:2028 (anonymous) @ mqtt.html:12 paho-mqtt.js:1054
> Uncaught DOMException: Failed to construct 'WebSocket': An insecure
> WebSocket connection may not be initiated from a page loaded over
> HTTPS.
>     at ClientImpl.LibraryFactory.ClientImpl._doConnect (https://myserver.com/pis/monitoring/paho-mqtt.js:1054:19)
>     at ClientImpl.LibraryFactory.ClientImpl.connect (https://myserver.com/pis/monitoring/paho-mqtt.js:887:10)
>     at Client.connect (https://myserver.com/pis/monitoring/paho-mqtt.js:2028:12)
>     at https://myserver.com/pis/monitoring/mqtt.html:12:8 LibraryFactory.ClientImpl._doConnect @ paho-mqtt.js:1054
> LibraryFactory.ClientImpl.connect @ paho-mqtt.js:887 Client.connect @
> paho-mqtt.js:2028 (anonymous) @ mqtt.html:12

错误消息非常清楚的问题

> Error paho-mqtt.js:1054 Mixed Content: The page at
> 'https://myserver.com/pis/monitoring/mqtt.html' was loaded over HTTPS,
> but attempted to connect to the insecure WebSocket endpoint
> 'ws://myserver.com:8083/mqtt'. This request has been blocked; this
> endpoint must be available over WSS.

浏览器正在强制执行安全来源策略。这意味着,从通过HTTPS加载的页面访问的任何资源都必须以同样安全的方式访问。因此,在这种情况下,如果您通过HTTP加载页面,则必须使用安全的Web套接字连接来连接到MQTT代理。

您需要在代理上启用Secure Websockets,并使用wss://URL或将useSSL: true添加到传递给client.connect()函数的选项中。

第二种选择是让代理为您提供网页代理,并在那里进行SSL/TLS终止。例如Nginx或Apache。

最新更新