Я пытаюсь получить рабочий пример mqttjs в nodejs. Я получаю эту ошибку при попытке выполнить мой файл main.js с помощью команды node main.js в командной строке Windows 10:
ошибка:
C:\Users\Rich\Documents\Code\nodejs\onoff\node_modules\mqtt\lib\connect\index.js:64
throw new Error('Missing protocol')
^
Error: Missing protocol
at Object.connect (C:\Users\Rich\Documents\Code\nodejs\onoff\node_modules\mqtt\lib\connect\index.js:64:13)
at Object.<anonymous> (C:\Users\Rich\Documents\Code\nodejs\onoff\main.js:2:20)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
код:
var mqtt = require('mqtt');
var client = mqtt.connect('192.168.0.22');
client.on('connect', function () {
client.subscribe('mydevice')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.info(message.toString())
client.end()
})





Это потому, что (как указано в сообщении об ошибке) вы пропустили протокол из URI, который необходимо передать методу connect().
Вы передали необработанный IP-адрес, но он должен быть URI, включая протокол и хост.
var client = mqtt.connect('mqtt://192.168.0.22')
Это показано в примерах в README.md, который включен в пакет как на github, так и на npm.
Это также описано в документации API:
mqtt.connect([url], options)
Connects to the broker specified by the given url and options and returns a Client.
The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp', 'tls', 'ws', 'wss'. The URL can also be an object as returned by URL.parse(), in that case the two objects are merged, i.e. you can pass a single object with both the URL and the connect options