node.js - 使用 NodeJS 的 Firebase 网络推送通知不起作用
问题描述
我正在构建一个使用 firebase 和 NodeJs 服务器发送 Web 推送通知的应用程序,但我收到“不匹配的凭据”错误,我该如何解决这个问题?
我首先生成一个 json 文件,该文件从控制台给了我“生成私钥”按钮,然后从我的服务器代码将管理 SDK 添加到我的应用程序中,这种方式
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://nodeproject-2bc3o.firebaseio.com"
});
然后我正在构建发送请求
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
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);
});
文档说,// This registration token comes from the client FCM SDKs
所以我使用从客户端获得的令牌作为我的令牌registrationToken
,我通过以下方式从客户端 javascript 代码中检索到该令牌,然后发送到服务器
messaging.getToken().then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
}
最后,在使用令牌从服务器发送消息后,我收到以下错误
errorInfo: {
code: 'messaging/mismatched-credential',
message: 'SenderId mismatch'
},
codePrefix: 'messaging'
}
检索客户端令牌,将其发送到服务器,然后使用它向客户端发送推送通知的正确方法是什么?或者我做错了什么?
解决方案
如果您使用 Firebase Cloud Functions 作为后端服务器,那么这serviceAccountKey.json
不是必需的,而且更简单。
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
这些行加载 firebase-functions 和 firebase-admin 模块,并初始化一个管理应用实例,可以从中进行 Cloud Firestore 更改。
而且,fcm 示例是https://github.com/firebase/functions-samples/tree/master/fcm-notifications
推荐阅读
- javascript - JavaScript 问题:在原始类型上调用 toString()
- matlab - 为什么我不能从服务器打开 matlab .m 文件
- javascript - 错误:使用props和创建动态路由时获取图片地址失败
- java - 根据参数类型区分黄瓜步骤定义
- c++ - 如何使用形态学操作去除不需要的噪音?
- django - 在 django 通用视图中访问 self.request.user.profile
- keras - 将 Embedding 层参数转换为 Lambda 层
- c - C程序通过scanf
- python - 查找字典列表中的最大值并返回键
- typescript - 错误 TS2339:只读类型上不存在属性