[英]Send push notifications with firebase-admin from nodejs
我有一个来自女巫的 Nodejs 项目,我需要向设备发送推送通知。 我在 firebase 中配置了应用程序,并从 firebase 控制台发送测试消息工作正常。 但是从nodeJs它不起作用,但响应消息是成功的。
回复
Successfully sent notification
{
responses: [
{
success: true,
messageId: 'projects/bioter-app/messages/0:1661888947319442%2fcd2f4df9fd7ecd'
}
],
successCount: 1,
failureCount: 0
}
发送消息的代码
import { initializeApp, cert } from "firebase-admin/app";
import { messaging } from "firebase-admin";
import path from "path";
export interface IPushNotificacion {
token: string,
data: {
title: string,
message: string
}
}
initializeApp({
credential: cert(path.join(__dirname, 'keys', 'bioter-app-firebase-adminsdk-11lci-9e163aab29.json'))
})
export const sendMessage = (messages: IPushNotificacion[]) => {
if (!messages.length) return
messaging().sendAll(messages)
.then(response => {
console.log(`Successfully sent notification`)
console.log(response)
})
.catch(err => {
console.log('Notification could not be sent ')
console.log(err)
})
}
我尝试阅读 firebase 管理文档以获取云消息,但它非常混乱。 https://firebase.google.com/docs/cloud-messaging/server
好吧,在我失去理智很长一段时间后,我发现
messaging().sendAll()
function 需要一个令牌和一个notification
属性,其中子项作为title
和body
。
如果您传递一个令牌和另一个属性,在我的案例数据中,它会返回成功但不发送通知。
Firebase 文档的摘要指出:
使用 FCM,您可以向客户端发送两种类型的消息:
- 通知消息:有时被认为是显示消息。 这些由 FCM SDK 自动处理。
- 数据消息:由客户端应用程序处理,需要显式实现代码来处理接收到的有效负载。
现在,查看上面的代码实现:
export interface IPushNotificacion {
token: string,
data: {
title: string,
message: string
}
}
很明显,您尝试发送data
消息而不是notification
消息,因此firebase-admin
您返回了成功消息。
话虽如此,如果您没有在客户端应用程序上明确定义代码来处理接收到的数据消息,那么应用程序将不知道如何处理该消息。 自然不产生任何结果/不显示通知。
因此,一旦您将结构更改为:
export interface IPushNotificacion {
token: string,
notification: {
title: string,
body: string
}
}
firebase-admin
定期向您的应用发送通知,您的应用直接显示,没有任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.