【问题标题】:FCM : getting ' Error: data must be a non-null object' error?FCM:得到“错误:数据必须是非空对象”错误?
【发布时间】:2020-11-11 13:52:29
【问题描述】:

我正在尝试通过 Firebase 云消息发送推送通知。我正在使用 Firebase admin sdk 在 fcm 中发送推送通知。我正在使用 nodejs

当我尝试发送推送消息时,...

我收到了这个错误

{ 
    code: 'messaging/invalid-payload',
    message: 'data must be a non-null object' },
   codePrefix: 'messaging'
 }

我的代码:

const admin = require('firebase-admin');

const serviceAccount = require(`${__dirname}/fet_firebase.json`);

    function sendPushNot(to, body, sendId, type) {
    
      const registrationToken = to;
      const notification = {};
    
      let message = { };
      const pbody = { body };
    
      if (type === 'User') {
        pbody.userId = sendId;
        notification.userId = sendId;
        notification.title = 'New user Follwed';
      }
      if (type === 'Post') {
        pbody.postId = sendId;
        notification.postId = sendId;
        notification.title = 'Post Liked';
      }
      if (type === 'Room') {
        pbody.roomId = sendId;
        notification.roomId = sendId;
        notification.title = 'New Chat messsage';
      }
    
      message = {
        data: JSON.stringify(pbody),
        token: registrationToken,
        notification
      };
    
      console.log('messgae',message);
    
      admin.messaging().send(message)
      .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent cloud message:', response);
      })
      .catch((error) => {
        console.log('Error sending cloud message:', error);
      });
    }

我以为身体是空的

但是console.log('messgae',message);的控制台输出是::

{
 data:
     '{"body":"pankaj Liked Your Post","postId":"5ed1055ddf0efd2a42f6a28a"}',
   token:
   'f2umP-jfQyeM1suN77zz7-:APA91bHKzfqfRnmuBom2PIDB8cCPwZtq28JCWLSi1OMPO55JRzyhFZJpTkkNyDu_StTYID-scu-grejaxxn3d4iR6Xidz9-JCk_h-bRsdGHe8nzMrIVsc8vZDFgayiFgJrJ53DaDzb9b',
  notification: { postId: 5ed1055ddf0efd2a42f6a28a, title: 'Post Liked'
 } 
}

所以body不为空

但我收到data must be a non-null object' error ..

为什么?

【问题讨论】:

    标签: node.js express firebase-cloud-messaging firebase-admin


    【解决方案1】:

    我通过用花括号包裹字符串化对象来解决这个问题

    data : { data: JSON.stringify(object) } // correct
    data : JSON.stringify(object) // will result to the described error.
    

    【讨论】:

    • 对我来说这看起来像SyntaxError。你能详细说明你的答案吗?
    【解决方案2】:

    数据必须是非空对象。上面的代码示例正在传递一个字符串。只需删除 JSON.stringify() 部分。

    【讨论】:

    • 那么你的对象中可能有非字符串值。数据对象只能有字符串值。类型签名:data?: { [key: string]: string };
    猜你喜欢
    • 2021-07-01
    • 2018-06-01
    • 1970-01-01
    • 2018-02-23
    • 2017-11-20
    • 1970-01-01
    • 2013-07-28
    • 2017-12-26
    • 2014-02-13
    相关资源
    最近更新 更多