错误:“数据必须仅包含字符串值”firebase 云消息传递

问题描述 投票:0回答:5

我正在尝试通过 FCM(Firebase 云消息传递)将一些数据从我的 node.js 服务器发送到 Android 客户端。发送时出现以下错误:“数据必须仅包含字符串值”。我的数据包含 2 个 JSONObject。我是否必须将它们转换为字符串,或者这里的方法是什么?谢谢。

var message = {
    notification:{
        "title": "Alert!",
        "body": position[0] + " has left Area: " + activeGeofences[i][1].name
      },
      data:{
        Geofence: activeGeofences[i][1],
        Position: position[1]
      },
    token: activeGeofences[i][0]
  };
android node.js firebase-cloud-messaging
5个回答
15
投票

要将任何 JSON 对象转换为字符串,您可以使用

JSON.stringify()
。然后,在接收端,您可以使用
JSON.parse()
(或您的平台的等效项)将字符串解析回树结构。


1
投票

你也可以这样做,因为它对我来说似乎更准确

data: {
       key1: "value1",
       key2: "value2",
        }

您只需确保 value1 或 value2 或任何 n 键的值对是字符串(如果它是 int 或其他任何会引发错误的值)。这可以让你免于解析东西。


0
投票

内部数据对象数据类型应始终为字符串。
如果您输入数字数据类型,则会发生错误。

let message = {
  notification: {
    title: payload.title,
    body: payload.message,
  },
  data: {
    name: 'sds',
    type: '2',
    _id: 'sdsd',
  },
  token: deviceToken,
};

0
投票

如果有人在 Python 上遇到困难。显然它必须是一个仅包含字符串的对象

body = json.dumps(data_object)
def send_notification(topic, title, body):
"""Send FCM notification to a specific topic"""
message = messaging.Message(
    topic=topic,
    data={"message": body},
    notification=messaging.Notification(
        title=title,
        body=body
    )
)

# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

0
投票

我也在为同样的错误而苦苦挣扎。问题是属性具有未定义的值。不幸的是,firebase 不允许任何数据属性的任何值未定义/为空

这是我所拥有的样本


{
    notification:{
        "title": "Alert!",
        "body": position[0] + " has left Area: " + activeGeofences[i][1].name
      },
      data:{
        Geofence: activeGeofences[i][1],
        Position: position[1],
        image: undefined
      },
    token: activeGeofences[i][0]
  };

如您所见,图像未定义。解决方案是删除具有未定义/空值的属性


{
    notification:{
        "title": "Alert!",
        "body": position[0] + " has left Area: " + activeGeofences[i][1].name
      },
      data:{
        Geofence: activeGeofences[i][1],
        Position: position[1],
      },
    token: activeGeofences[i][0]
  };
© www.soinside.com 2019 - 2024. All rights reserved.