FCM:收到“错误:数据必须是非空对象”错误?

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

我正在尝试通过 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'
 } 
}

所以身体不为空

但我越来越

data must be a non-null object' error
..

为什么?

node.js express firebase-cloud-messaging firebase-admin
3个回答
10
投票

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

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

2
投票

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

JSON.stringify()
部分即可。


0
投票
data : { data: JSON.stringify(object) } // correct
data : { data : JSON.stringify(object) } // incorrect
data : { data = JSON.stringify(object) } // incorrect
data : JSON.stringify(object) // incorrect
© www.soinside.com 2019 - 2024. All rights reserved.