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

MQTTX脚本中fetch/axios/XMLHttpRequest未定义问题求助

解决MQTTX脚本中无法使用网络请求API的问题

问题原因

MQTTX的Script运行环境是受限沙箱,未提供浏览器或Node.js标准的网络请求API(如fetch、XMLHttpRequest),也不支持引入第三方库(如axios),直接调用这些方法会抛出ReferenceError。

可行解决方案

1. 搭建中间MQTT转发服务

通过独立服务(如Node.js)订阅目标MQTT主题,收到符合条件的消息后,由该服务发起OneSignal的API请求,完全绕过MQTTX的脚本限制。

示例Node.js服务代码:

const mqtt = require('mqtt');
const fetch = require('node-fetch');

// MQTT连接配置
const mqttClient = mqtt.connect('mqtt://your-mqtt-broker-url');
// OneSignal配置
const ONES_APP_ID = 'your-app-id';
const REST_API_KEY = 'your-rest-api-key';
const API_URL = 'https://onesignal.com/api/v1/notifications';
const ANDROID_CHANNEL_ID = 'your-android-channel-id';

mqttClient.on('connect', () => {
  console.log('Connected to MQTT broker');
  mqttClient.subscribe('your-target-topic'); // 订阅MQTTX发布的目标主题
});

mqttClient.on('message', async (topic, payload) => {
  try {
    const object = JSON.parse(payload.toString());
    // 匹配原脚本触发条件
    if (object.type === 'error') {
      const postData = {
        included_segments: ["Total Subscriptions"],
        app_id: ONES_APP_ID,
        contents: { en: "Something went wrong" },
        headings: { en: "❌ - Error" },
        data: { custom_data: "some_value" },
        android_channel_id: ANDROID_CHANNEL_ID,
        ios_sound: "alarm.wav"
      };

      const response = await fetch(API_URL, {
        method: "POST",
        body: JSON.stringify(postData),
        headers: {
          "Authorization": REST_API_KEY,
          "Accept": "application/json",
          "Content-Type": "application/json",
        },
      });

      console.log('OneSignal API response:', await response.json());
    }
  } catch (err) {
    console.error('Error processing message:', err);
  }
});

2. 测试MQTTX内置HTTP扩展API

部分版本的MQTTX可能提供未公开的内置HTTP请求方法,可在脚本中测试验证:

// 测试内置HTTP请求方法(仅作尝试,不保证存在)
async function testHttpRequest() {
  try {
    const response = await http.post(API_URL, postData, {
      headers: {
        "Authorization": REST_API_KEY,
        "Content-Type": "application/json"
      }
    });
    console.log(response);
  } catch (err) {
    console.log('内置HTTP方法不存在:', err);
  }
}

若测试失败,说明环境确实无网络请求能力,优先采用第一种方案。

3. 外部脚本替代MQTTX脚本逻辑

如果使用MQTTX桌面版,可通过系统级脚本(如Python)结合MQTT客户端库监听消息,发起HTTP请求:

import paho.mqtt.client as mqtt
import requests
import json

# 配置信息
MQTT_BROKER = "your-mqtt-broker-url"
MQTT_TOPIC = "your-target-topic"
ONES_APP_ID = "your-app-id"
REST_API_KEY = "your-rest-api-key"
API_URL = "https://onesignal.com/api/v1/notifications"
ANDROID_CHANNEL_ID = "your-android-channel-id"

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(MQTT_TOPIC)

def on_message(client, userdata, msg):
    payload = json.loads(msg.payload.decode())
    if payload.get("type") == "error":
        post_data = {
            "included_segments": ["Total Subscriptions"],
            "app_id": ONES_APP_ID,
            "contents": {"en": "Something went wrong"},
            "headings": {"en": "❌ - Error"},
            "data": {"custom_data": "some_value"},
            "android_channel_id": ANDROID_CHANNEL_ID,
            "ios_sound": "alarm.wav"
        }
        headers = {
            "Authorization": REST_API_KEY,
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        response = requests.post(API_URL, json=post_data, headers=headers)
        print("OneSignal response:", response.json())

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(MQTT_BROKER, 1883, 60)
client.loop_forever()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:57:45