如何使用 Node.js 向所有 android 设备发送 FCM 通知

How to send FCM notification to all android devices using Node.js

我想将通知发送到我的 Android 使用 Ionic t 从 Node.Js 代码开发的应用程序。我尝试了以下代码并获得 Exactly one of topic, token or condition is required.

如何无条件地向所有用户发送通知?

var serviceAccount = require("/path/to/config.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://myApp.firebaseio.com"
});

var message = {
    notification: {
      title: '$GOOG up 1.43% on the day',
      body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
    }
  };


admin.messaging().send(message).then(res=>{
    console.log("Success",res)
}).catch(err=>{
    console.log("Error:",err)
})

如果你想向所有用户发送通知,那么最好的办法是将用户注册到某个主题,例如food然后每个注册到该主题的人都会收到通知。

在上面的代码中,您收到该错误是因为您没有提供要向谁发送通知。

如果令牌:

var registrationToken = 'YOUR_REGISTRATION_TOKEN'; <-- token of user
var message = {
notification: {
  title: '$GOOG up 1.43% on the day',
  body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  }
token: registrationToken
};

如果主题:

var topic = 'food';
var message = {
notification: {
  title: '$GOOG up 1.43% on the day',
  body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  }
  topic: topic
};

更多信息在这里:

https://firebase.google.com/docs/cloud-messaging/admin/send-messages