Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm attempting to get a working example of mqttjs in nodejs. I'm receiving this error while attempting to execute my main.js file using command
node main.js
in Windows 10 cmd prompt:
error:
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
code:
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.log(message.toString())
client.end()
It's because (as the error states) you've missed the protocol out of the URI that needs to be passed to the connect()
method.
You have passed a raw IP address, but it needs to be a URI, including a protocol and a host.
var client = mqtt.connect('mqtt://192.168.0.22')
This is shown in the examples in the README.md that is included with the package both on github and npm.
It is also described in the API docs:
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
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.