How to send message to multiple android devices using FCM in Node js?

烈酒焚心 提交于 2021-02-07 19:49:37

问题


I tried sending message to single device i.e. to single Registration id and it worked fine but when tried to add multiple Registration Ids it gives 'InvalidServerResponse' error. e.g. Works for regTokens = 'regId1'; But doesn't work for regTokens = ['regId1','regId2'];

var FCM = require('fcm-node');
// Add API Key
var fcm = new FCM('<server-key>');

exports.sendMessage = function (regTokens, messageToSend, callback) {
  var message = { //this may vary according to the message type (single recipient, multicast, topic, et cetera)
      to: regTokens,

      data: { 
        ar_message: messageToSend
      }
  };

    fcm.send(message, function(err, response){
        if (err) {
            console.log("Something has gone wrong!",err);
        } else {
            console.log("Successfully sent with response: ", response);
        }
        callback(err, 'Success');
      });
}

回答1:


Update: For v1, it seems that registration_ids is no longer supported. It is strongly suggested that topics be used instead.


When sending to specified multiple registration tokens, you must use registration_ids instead of to. From the docs (emphasis mine):

This parameter specifies the recipient of a multicast message, a message sent to more than one registration token.

The value should be an array of registration tokens to which to send the multicast message. The array must contain at least 1 and at most 1000 registration tokens. To send a message to a single device, use the to parameter.

Multicast messages are only allowed using the HTTP JSON format.

var message = {
    registration_ids: regTokens,

   data: { 
        ar_message: messageToSend
   }
  };



回答2:


An update for this thread: Use admin.messaging.Messaging.sendToDevice() to send messages to multiple android devices.

https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging#sendToDevice

messaging.sendToDevice(registrationTokens, payload, options)

  • registrationTokens: Array of String (Tokens of the recipients)

  • payload: Message payload

  • options: (Optional) admin.messaging.MessagingOptions



来源:https://stackoverflow.com/questions/42391683/how-to-send-message-to-multiple-android-devices-using-fcm-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!