【问题标题】:FCM message payload errors, Nested object within data object errors outFCM 消息有效负载错误,数据对象内的嵌套对象错误输出
【发布时间】:2018-02-04 17:45:57
【问题描述】:

根据 react-native-fcm 包,您可以在 FCM 消息传递有效负载的数据对象中包含自定义嵌套对象。

according to this post by the package author

像这样:

var payload = {
    data: {
        custom_notification: {
            title: 'title',
            body: 'body',
            priority: 'high',
            id: 'id',
            group: 'group'
        }
    }
};

这是为了在所有应用程序状态下接收抬头通知,如果您只执行通知负载或数据负载,则不会发生这种情况。

当我在我的云功能中实现此功能时,我收到以下错误:

Error: Messaging payload contains an invalid value for the "data.custom_notification" property. Values must be strings.

所以我不知道其他人如何成功地使用它?

我想知道我的环境是否存在问题,或者是由 firebase 支持(并且在文档中)提供给我的以下测试有效负载错误:

var payload = {
"to":"FCM_TOKEN",
"data": {
"type":"MEASURE_CHANGE",
"body": "test body",
"title": "test title",
"color":"#00ACD4",
"priority":"high",
"id": "id",
"show_in_foreground": true
}
};

我收到以下错误:

Error sending message stringify: {"code":"messaging/invalid-payload","message":"Messaging payload contains an invalid \"to\" property. Valid properties are \"data\" and \"notification\"."}

已经在这几天了,希望我能在这方面得到一些帮助。

提前致谢!

【问题讨论】:

  • 尝试使用以下方法对有效负载进行字符串化:body: JSON.stringify({ your json object })

标签: javascript android firebase react-native firebase-cloud-messaging


【解决方案1】:

所以我刚刚意识到(经过几天的搜索)包 react-native-fcm 使用的发送方法与 admin.messaging().sendToDevice(token, payload, options) 不同。我已经使用了一段时间了,并没有意识到它实际上并不是要与这个库一起使用的,或者至少在这种情况下是这样。主要是因为使用 admin.messaging() 一切正常,直到我想要在所有应用程序状态中显示通知。

另一种方法是这样的

  sendData(token) {
    let body = {
        "to": token,
      "data":{
            "title": "Simple FCM Client",
            "body": "This is a notification with only DATA.",
            "sound": "default",
            "click_action": "fcm.ACTION.HELLO",
            "remote": true
        },
        "priority": "normal"
    }

    this._send(JSON.stringify(body), "data");
  }

  _send(body, type) {
    let headers = new Headers({
        "Content-Type": "application/json",
        "Content-Length": parseInt(body.length),
      "Authorization": "key=" + FirebaseConstants.KEY
    });

    fetch(API_URL, { method: "POST", headers, body })
        .then(response => console.log("Send " + type + " response", response))
        .catch(error => console.log("Error sending " + type, error));
  }

您可以使用此方法在数据对象中使用嵌套对象。不幸的是,文档对此并不是很清楚,直到现在我什至没有意识到有一个例子。当然,这可能只是我。

【讨论】:

    【解决方案2】:

    当使用data 消息负载时,声明使用字符串键值对,因此您可以做的是将custom_notification 的值作为JSON 字符串,将它们包含在" " 中。

    对于提供的示例负载,您实际上是否在to 参数中使用了FCM_TOKEN?您应该用实际的令牌替换它。

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      相关资源
      最近更新 更多