Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FCM : getting ' Error: data must be a non-null object' error?

I am trying to send a push notification via Firebase cloud messaging. I am using Firebase admin sdk to send push notification in fcm . I am using nodejs

When I am trying to send a push msg , ...

I am getting this error

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

My code :

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);
      });
    }

I thought that body is null

But the console output of console.log('messgae',message); is ::

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

So the body is not null

But I am getting data must be a non-null object' error ..

Why?

like image 375
Ragesh D Antony Avatar asked Jun 23 '20 10:06

Ragesh D Antony


1 Answers

I fixed this by wrapping the stringified object with curly braces

data : { data: JSON.stringify(object) } // correct
data : JSON.stringify(object) // will result to the described error.
like image 167
gel drif Gelu Avatar answered Nov 15 '22 03:11

gel drif Gelu