I am trying to get a simple mqtt broker set up and access it from a web page. I have had pretty much 0 luck.
I’ve got mosquitto 2.0.14 downloaded and running. Here’s my configuration file:
listener 1883 listener 9001 protocol websockets
This generates the following log when I run mosquitto -c mosquitto_conf -v
1637948154: mosquitto version 2.0.14 starting 1637948154: Config loaded from mosquitto.conf. 1637948154: Opening ipv6 listen socket on port 1883. 1637948154: Opening ipv4 listen socket on port 1883. 1637948154: Opening websockets listen socket on port 9001. 1637948154: mosquitto version 2.0.14 running
Here’s my html file, which I simply open in the browser. It uses Paho’s js client.:
<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script> <script type="text/javascript" language="javascript"> var mqtt; var reconnectTimeout = 2000; var host = "192.168.1.94"; var port = 9001; function onConnect() { console.log("Connected"); message = new Paho.MQTT.Message("hello"); message.destinationName = "sensor1"; mqtt.send(message); } function mqttConnect() { console.log("Connecting to " + host + ":" + port); mqtt = new Paho.MQTT.Client(host, port, "clientjs"); var options = { timeout: 3, onSuccess: onConnect, }; mqtt.connect(options); } </script> </head> <body> <script> mqttConnect(); </script> </body> </html>
I’m using a guide from this website: http://www.steves-internet-guide.com/using-javascript-mqtt-client-websockets/
It errors out with the following console error in the browser:
WebSocket connection to 'ws://127.0.0.1:9001/mqtt' failed
I have been having a hard time finding an updated tutorial that works. My ultimate goal is to create a react app that connects to an mqtt broker via websockets and receives messages to update state in redux.
Questions: How do I get the js client to connect? How do I set the host for mosquitto? Can I use a diff host like myhost.local or am I stuck using 127.0.0.1 or whatever I see when I run ipconfig (I’m on windows)?
Advertisement
Answer
You need to add allow_anonymous true
to allow users to connect without supplying a username/password.
This is part of the set of changes introduced in v2.0 to improve the default security posture of mosquitto out of the box.