如何在Node.js中使用FCM向多个安卓设备发送消息?

5

我尝试向单个设备发送消息,即单个注册ID,它可以正常工作。但是,当我尝试添加多个注册ID时,会出现“InvalidServerResponse”错误。 例如:对于regTokens ='regId1'可以运行; 但是对于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');
      });
}


如果单独发送,它适用于所有的注册ID。但是对于数组则无效。 - Abhilasha
1
请确保代码是自包含的。现在,我们不知道regTokens是什么,这很可能是它失败的关键原因。 - Frank van Puffelen
4个回答

12
更新:对于 v1 版本,似乎不再支持使用 registration_ids。强烈建议改用主题代替。
当要发送到特定的多个注册令牌时,必须使用 registration_ids 而不是 to。从文档中可知(重点在于我):
此参数指定多播消息的接收者,即发送到多个注册令牌的消息。 值应为一组注册令牌,其最少含有 1 个,最多含有 1000 个注册令牌,以便向其中发送多播消息。要向单个设备发送消息,请使用 to 参数。 只允许使用 HTTP JSON 格式进行多播消息。
var message = {
    registration_ids: regTokens,

   data: { 
        ar_message: messageToSend
   }
  };

4

0
var message = {
            // to : "token", //for single device
            registration_ids: ["token1", "token2"], // for Multiple device
            collapse_key: 'your_collapse_key',
            notification: notify,
            data: payload,
         };

0
var fetch = require('node-fetch');

send_fcm_notifications()
function send_fcm_notifications(){ 

// notification object with title and text

var notification = {
  'title': 'Best Deals',
  'text': 'Mobile Devices at 50% off. Only for today'
};

// fcm device tokens array

var fcm_tokens = ["Key 1", "Key 2"]

var notification_body = {
    'notification': notification,
          'registration_ids': fcm_tokens
  }


fetch('https://fcm.googleapis.com/fcm/send', {

        'method': 'POST',

        'headers': {
          // replace authorization key with your key
          'Authorization': 'key=' + 'Authorization Key',
          'Content-Type': 'application/json'
        },

         'body': JSON.stringify(notification_body)
      })
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) 
        console.error(error);
      })
}

请考虑对你发布的代码进行[编辑],以解释你的答案。 - David Buck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接