javascript - FCM 消息负载错误,数据对象内的嵌套对象错误

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

根据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\"."}

我已经这样做了好几天了,希望我能得到一些帮助。

提前致谢!

最佳答案

所以我刚刚意识到(经过几天的搜索)包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));
  }

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

关于javascript - FCM 消息负载错误,数据对象内的嵌套对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45902343/

相关文章:

android - 如何在后台播放音频

javascript - 如何获取 firestore 文档中的字段?

javascript - 循环随机变量和数组来解决多次包含 JavaScript 的问题

java - AsyncTask 未按预期完成

android - Kotlin 顶层函数 vs 对象函数

android - 根据来自 Firebase 的优先级对数据进行排序并将其显示在 FirebaseRecyclerAdapter 中

android - 如何查询 Firebase 数据库而不显示基于 bool 值的值

javascript - 使用 AngularJS 服务构建 html 部分

javascript - 如何从字符串中获取特定值?

javascript - 带有外部 map 着色的谷歌地图多边形