I try to connect my webapp with my MQTT-Broker. I decide to use MQTT.js, but there is an error in my code:
Uncaught TypeError: n.createConnection is not a function
at t.exports (mqtt.min.js:1:29576)
at T.streamBuilder (mqtt.min.js:1:39683)
at T._setupStream (mqtt.min.js:1:6556)
at new T (mqtt.min.js:1:5968)
at Function.u [as connect] (mqtt.min.js:1:39286)
at (index):23:29
The exception will be thrown in line const client = mqtt.connect(broker);
.
I don't know, how to solve this issue, I hope you can help me.
Here is a minimal example of my code:
<!DOCTYPE html>
<html>
<head>
<title>MQTT Data Display</title>
<script src="mqtt.min.js"></script>
</head>
<body>
<h1>MQTT Data Display</h1>
<h2>Receiving Data:</h2>
<textarea id="dataField" rows="5" cols="50" readonly></textarea>
<h2>Input text:</h2>
<input type="text" id="inputField" />
<button onclick="publishMessage()">Send</button>
<script>
// MQTT Broker config
const broker = 'mqtt:<BrokerURL>';
const topic = 'your-mqtt-topic';
// create MQTT Client
const client = mqtt.connect(broker);
// connect MQTT Client
client.on('connect', function () {
console.log('MQTT connected');
client.subscribe(topic);
});
// Receive new message
client.on('message', function (topic, message) {
const data = message.toString();
const dataField = document.getElementById('dataField');
dataField.value = data;
});
// publish messsage
function publishMessage() {
const inputField = document.getElementById('inputField');
const message = inputField.value;
client.publish(topic, message);
}
</script>
</body>
</html>