如何使用node-fcm将通知发送到多个设备

时间:2020-08-11 12:46:52

标签: node.js express push-notification firebase-cloud-messaging

关闭应用程序后通知不起作用

const令牌= [“ AAASDfsadfasdfaFDSDFSDLFJLSDAJF; DSJFAsdfdsfsdf”];

app.get('/send-notfication', (req, res) => {
        
        var FCM = require('fcm-node');
        var fcm = new FCM(serverKey);
     
        var messageToSend = "Hi there this is message";

        var message = {
         to: token,

         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.results);
                res.send("Successfully sent")
            }
        });
    })

问题是如何在其中设置通知标题的?并且通知不起作用,应用程序既不在后台也没有在前台关闭,为什么?

2 个答案:

答案 0 :(得分:1)

尝试这种方式..

如果令牌位于数组中并将信息传递到数据对象中,请使用“ registration_ids”而不是“ to”。

app.get("/send-fcm-notification", (req, res) => {
  var FCM = require("fcm-node");
  var fcm = new FCM(serverKey);
  var message = {

   registration_ids: token,

    data: {
      title: "Hi there this is title",
      message: "Hi there this is message"
    },

  };

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

答案 1 :(得分:0)

有两种选择:

选项 1:这是一个用户(一个设备令牌)。

var message = {

   to: token,

    data: {
      title: "Hi there this is title",
      message: "Hi there this is message"
    },

  };

结果:

成功 JSON

选项 2:这适用于多个用户(多个设备令牌)..

     var message = {

   registration_ids: token,

    data: {
      title: "Hi there this is title",
      message: "Hi there this is message"
    },

  };

结果:

成功 JSON

注意:创建通知数据只有一处不同。 使用 registration_ids 而不是 to