简体   繁体   English

尝试订阅 Firebase Cloud Messaging 上的主题时出现错误

[英]Trying to subscribe to topic on Firebase Cloud Messaging gives Error

When i try to subscribe to a topic i get the following error:当我尝试订阅某个主题时,出现以下错误:

.subscribeToTopic is not a function .subscribeToTopic 不是函数

const messaging = firebase.messaging();
      messaging
        .requestPermission()
        .then(() => {
          return messaging.getToken();
        })
        .then(token => {
          messaging
            .subscribeToTopic(token, 'allUsers')
            .then(response=> {
              console.log(JSON.stringify(response));
            })
            .catch(function(error) {
              console.log('Error subscribing to topic:', error);
            });
        })
        .catch(err => {
          console.log('Unable to get permission to notify.', err);
        });

If I remove that line of .subscribeToTopic and add a POST call via http it works using the following url: https://iid.googleapis.com/iid/v1/TOKEN/rel/topics/TOPIC_NAME如果我删除.subscribeToTopic的那一行并通过 http 添加一个 POST 调用,它可以使用以下 url: https ://iid.googleapis.com/iid/v1/TOKEN/rel/topics/TOPIC_NAME

I took a look to this question and the docs Cloud Messaging in Cloud Functions: admin.messagin(...).send is not a function我查看了这个问题和文档Cloud Messaging in Cloud Functions: admin.messagin(...).send is not a function

https://firebase.google.com/docs/cloud-messaging/js/topic-messaging https://firebase.google.com/docs/cloud-messaging/js/topic-messaging

You need to use the method send not sendToTopic :您需要使用方法send而不是sendToTopic

// The topic name can be optionally prefixed with "/topics/".
var topic = 'highScores';

var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic
};

// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

send() was released and replaced sendtotopic/sendtodevice in version FCM v1 send()在 FCM v1 版本中被发布并替换了sendtotopic/sendtodevice

https://firebase.googleblog.com/2018/02/firebase-cloud-messaging-v1-now.html https://firebase.googleblog.com/2018/02/firebase-cloud-messaging-v1-now.html

https://firebase.google.com/docs/cloud-messaging/js/topic-messaging https://firebase.google.com/docs/cloud-messaging/js/topic-messaging

ah i solved it by handling on backend side ( nodeJS ) where the documentation is easy to handle topic.啊,我通过在文档易于处理的主题的后端(nodeJS)处理来解决它。

so in this case we have alr generate token on frontend side then in backend (nodeJS) we tried to subscribe to topic by the token.所以在这种情况下,我们在前端生成令牌然后在后端(nodeJS)我们尝试通过令牌订阅主题。

so in frontend end when we stream or firebase.messaging().onMessage(payload => { would like to trigger and show the message by topic.所以在前端当我们流式传输或firebase.messaging().onMessage(payload => {想触发并按主题显示消息。

FYI : https://github.com/firebase/firebase-js-sdk/issues/5289#issuecomment-899542765仅供参考: https ://github.com/firebase/firebase-js-sdk/issues/5289#issuecomment-899542765

so from the link we know that Notification.vue所以从链接我们知道Notification.vue

// these from frontend side ( for example vueJS )
import firebase from 'firebase/app'
import 'firebase/messaging'
// firebase only for get token, onMessaging, request permission check, there is no function to subscribe topic by the token, so we handle on backend side my alternative

then in server.js然后在server.js

// these from backend side ( for examle nodeJS )
const { admin } = require('./firebase-config');
// admin.messaging().sendToTopic()
// admin.messaging().subscribeToTopic()
// admin.messaging().sendToDevice()

if you are looking for the firebase-config.js here is如果您正在寻找firebase-config.js这里是

/*
 * Initialize firebase
 */
var admin = require("firebase-admin");

var serviceAccount = require("./firebase.json"); // you can get the .json file on firebase service account .

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://project-xxxxxxx.firebaseio.com"
});
module.exports.admin = admin

my implementation :我的实现:

app.get('/firebase/notification', (req, res)=>{
  const registrationToken = req.body.registrationToken;

  admin.messaging().subscribeToTopic(registrationToken, 'myTopic')
      .then(response => {
        console.log('Successfully subscribed to topic:', response)

        const options =  notification_options;
        const message_notification = {
          notification: {
            title: 'Yogi Arif Widodo',
            body: '2 10 pm',
            url: 'https://localhost:8080',
            other: 'other data',
          }
        };
        admin.messaging().sendToTopic('myTopic', message_notification, options).then( response => {

so when i tested on firebase console send by topic myTopic my Notification.vue trigger these code所以当我在firebase控制台上测试时,我的主题myTopic我的Notification.vue会触发这些代码

firebase.messaging().onMessage(payload => {
.....console.log
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM