dottedquad
dottedquad

Reputation: 1391

nodejs mqttjs Missing protocol error

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()
})

Upvotes: 3

Views: 7461

Answers (1)

hardillb
hardillb

Reputation: 59781

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

Upvotes: 14

Related Questions