You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native用MQTT连接Azure IoT Hub遇未授权错误求助

React Native通过MQTT连接Azure IoT Hub并发送消息的解决方案

问题根源

React Native的MQTT库(如sp-react-native-mqtt)依赖原生MQTT客户端实现,和Node.js的mqtt库在TLS配置、SAS Token传递逻辑上存在细微差异,导致授权验证失败。

关键修正点

  • 将protocolVersion设置为3(部分React Native MQTT库对MQTT 3.1.1支持更稳定,Azure IoT Hub完全兼容该版本)
  • 简化username格式,移除api-version参数(Node.js库兼容带参数的格式,但React Native原生库可能无法解析)
  • 确保TLS配置显式开启,部分库需要明确指定安全连接选项

完整实现代码

首先安装依赖:

npm install sp-react-native-mqtt --save

编写业务代码:

import { MqttClient } from 'sp-react-native-mqtt';

const deviceId = "exampledeviceid";
const iotHubName = "iotc-example-iotc-name";
// 简化username,去掉api-version参数
const userName = `${iotHubName}.azure-devices.net/${deviceId}`;
const iotHubTopic = `devices/${deviceId}/messages/events/`;
const sasToken = 'examplesastoken';

// 初始化MQTT客户端
const client = new MqttClient({
  uri: `mqtts://${iotHubName}.azure-devices.net:8883`,
  clientId: deviceId,
  username: userName,
  password: sasToken,
  tls: true,
  keepalive: 10,
  clean: false,
  protocolVersion: 3, // 使用MQTT 3.1.1协议
  connectTimeout: 30000,
});

// 监听连接成功事件
client.on('connect', () => {
  console.log('已连接到Azure IoT Hub');
  // 发送消息,指定QoS=1确保送达
  client.publish(iotHubTopic, JSON.stringify({ id: 12145 }), { qos: 1 }, (err) => {
    if (err) {
      console.error('消息发送失败:', err);
    } else {
      console.log('消息发送成功');
      // 发送完成后断开连接
      client.end();
    }
  });
});

// 监听连接错误事件
client.on('error', (error) => {
  console.error('连接错误:', error);
});

// 启动连接
client.connect();

额外排查要点

  • 确认SAS Token未过期,且权限包含iothub.send(发送消息权限)
  • 测试时关闭设备VPN或代理,避免网络拦截TLS连接
  • 若仍报错,可尝试替换为react-native-native-mqtt库,该库基于原生Paho MQTT客户端,兼容性更强

内容的提问来源于stack exchange,提问作者Gaurav Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 00:45:16