Home > Software design >  Cannot connect to MQTT Broker from ReactJS
Cannot connect to MQTT Broker from ReactJS

Time:11-16

I'm facing issues while connecting to my local MQTT Broker running in docker.

Here is my connection file:

import mqtt from 'mqtt';
const client = mqtt.connect({
  host: 'ws://192.168.31.46',
  port: 1883,
});
client.on('connect', () => {
  console.log('Connected');
  client.subscribe('SEND_MESSAGE', function (topic, message) {
    console.log({ topic, message });
  });
});
export default client;

CodePudding user response:

The port number is (99.9%) wrong, port 1883 is the native MQTT port not MQTT over WebSockets. What the correct port is will depend on how you have configured the broker (Assuming mosquitto, it does not have a WebSocket listener defined by default)

Also if the mqtt.connect() function is asking for a hostname and port then you shouldn't be give a URL to the post field. Remove the ws:// from the start.

  • Related