Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Browserified MQTT.js defaults to connecting to localhost instead of server URL #1730

Closed
dstolpmann opened this issue Nov 7, 2023 · 3 comments · Fixed by DariuszPiskorowski/aihomeNodeProject#2

Comments

@dstolpmann
Copy link

I am using the MQTT.js version from https://unpkg.com in the browser and experience the following issue.

In old versions (<=4.1.0), MQTT.js used to connect to the host that served the website and also used the same port if connect() was called without an URL. I do not know if it also selected wss over ws if the page was served via HTTPS, as I never used TLS.

Starting with 4.2.1 (4.2.0 does not work in the browser) and also in the current 5.1.4 release, calling connect() without an URL always connects to ws:https://localhost/.

This change in behavior was probably introduced in #1108.

I worked around this issue by using the following command:

mqtt.connect((location.protocol == "https:" ? "wss" : "ws") + ":https://" + location.hostname + ":" + location.port)
@robertsLando
Copy link
Member

@BrandonSmith would you like to submit a pr to fix this issue? you could use the is-browser const to detect the environment and based on that use localhost or the other default url

@haihuynhDF
Copy link

I also meet this issue when trying to connect MQTT from ReactJS

It connects to localhost instead of the host which I config in the option

But it works when I connect from NodeJS

This is my source code

const opt: mqtt.IClientOptions = {
  host,
  protocol: "mqtt",
  clientId,
  clean: true,
  key,
  cert,
  ca,
  reconnectPeriod: 0,
};

const client: MqttClient = mqtt.connect(opt);

client.on('connect', () => {
  console.log('client connected');
  client.publish(
    `topic`,
    "abc",
  );
})

@robertsLando
Copy link
Member

You should not provide an host in options in order to have it connecting to document url

options.hostname = parsed.hostname

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants