gpt4 book ai didi

javascript - 尝试订阅 Firebase Cloud Messaging 主题时出现错误

转载 作者:行者123 更新时间:2023-12-02 22:07:56 25 4
gpt4 key购买 nike

当我尝试订阅某个主题时,出现以下错误:

.subscribeToTopic is not a function

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

最佳答案

啊,我通过在后端(nodeJS)处理来解决这个问题,其中文档很容易处理主题。

所以在这种情况下,我们在前端生成 token 然后在后端(nodeJS)我们尝试通过 token 订阅主题。

因此,当我们流式传输或 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
}

关于javascript - 尝试订阅 Firebase Cloud Messaging 主题时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59659877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com