簡體   English   中英

嘗試訂閱 Firebase Cloud Messaging 上的主題時出現錯誤

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

當我嘗試訂閱某個主題時,出現以下錯誤:

.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);
        });

如果我刪除.subscribeToTopic的那一行並通過 http 添加一個 POST 調用,它可以使用以下 url: https ://iid.googleapis.com/iid/v1/TOKEN/rel/topics/TOPIC_NAME

我查看了這個問題和文檔Cloud Messaging in Cloud Functions: admin.messagin(...).send is not a function

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

您需要使用方法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()在 FCM v1 版本中被發布並替換了sendtotopic/sendtodevice

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

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

啊,我通過在文檔易於處理的主題的后端(nodeJS)處理來解決它。

所以在這種情況下,我們在前端生成令牌然后在后端(nodeJS)我們嘗試通過令牌訂閱主題。

所以在前端當我們流式傳輸或firebase.messaging().onMessage(payload => {想觸發並按主題顯示消息。

僅供參考: https ://github.com/firebase/firebase-js-sdk/issues/5289#issuecomment-899542765

所以從鏈接我們知道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

然后在server.js

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

如果您正在尋找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

我的實現:

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 => {

所以當我在firebase控制台上測試時,我的主題myTopic我的Notification.vue會觸發這些代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM