为什么Reactjs mqtt客户端url返回wss?
问题描述:
下面的代码在使用时效果很好node client_test.js
。但是,当我把这个reactjs我得到这个错误:为什么Reactjs mqtt客户端url返回wss?
(unknown) WebSocket connection to 'wss://dev.xxx.com:8083/' failed: Error in connection establishment: net::ERR_INSECURE_RESPONSE
这个URL总是转换为wss
协议。我不知道为什么会发生这种情况。
var mqtt = require('mqtt')
var options = {
//port: 8083,
//host: 'dev.xxx.com',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'xxx',
password: new Buffer('xxx'),
keepalive: 10,
reconnectPeriod: 1000,
protocolId: 'MQIsdp',
protocolVersion: 3,
clean: true,
encoding: 'utf8',
//protocol: 'mqtts',
rejectUnauthorized : false,
will: {
topic: 'node/status',
payload: new Buffer('offline')
}
};
var client = mqtt.connect('mqtts://dev.xxx.com:8083', options)
client.on('connect', function() {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
})
答
由于ReactJS在浏览器中运行,浏览器沙箱只允许它做WS(S)连接的不是本地MQTT所需的原始套接字连接。
的MQTT库的URL自动转换成一个可以尝试,并在浏览器(即安全WebSocket连接)使用
你需要确保你的经纪人支持安全的WebSockets连接,如果你想使用它与ReactJS
谢谢,@hardillb有用的答案 –