node.js - 如何在node.js中集成FCM以进行推送通知?

标签 node.js firebase push-notification firebase-cloud-messaging

我想在 Node.js 中使用 FCM 添加推送通知。为此我尝试了 this

以及 thisalso this

我的nodejs代码

var FCM = require('fcm-node');

var serverkey = 'SERVERKEY';  
var fcm = new FCM(serverkey);
var message = {  
			to : req.body.userToken,
			collapse_key : 'XXX',
			data : {
					my_key: 'my value', contents: "abcv/"
			},
			notification : {
					title : 'Title of the notification',
					body : 'Body of the notification'
			}
	};

fcm.send(message, function(err,response){  
if(err) {
	console.log(message);
       console.log("Something has gone wrong !");
 } else {
     console.log("Successfully sent with resposne :",response);
   }
});	

每当我尝试运行此代码并启动我的服务器时,我总是在控制台中收到此错误。

 /var/www/html/chatApp/node_modules/fcm-node/lib/fcm.js:10
 function FCM(accountKey, proxy_url=null) {
                              ^
 SyntaxError: Unexpected token =
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/var/www/html/chatApp/node_modules/fcm-node/index.js:1:80)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)

有人可以解释一下我做错了什么吗?

最佳答案

我使用 firebase-admin 包发送通知 ( https://firebase.google.com/docs/cloud-messaging/admin/send-messages )

var admin = require("firebase-admin");

var serviceAccount = require("./firebase-adminSDK.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
});
const messaging = admin.messaging()
    var payload = {
        notification: {
            title: "This is a Notification",
            body: "This is the body of the notification message."
        },
        topic: 'topic'
        };


    messaging.send(payload)
    .then((result) => {
        console.log(result)
    })

可以按照 https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app 中的步骤下载 firebase-adminSDK.json

此代码将向主题“topic”发送通知,但是,firebase-admin 软件包允许向特定设备发送通知。

关于node.js - 如何在node.js中集成FCM以进行推送通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52127390/

相关文章:

node.js - 端口*和*路径上的 NodeJS 套接字?

javascript - 为什么 Node.js 中的函数未定义

android - Firebase 应用崩溃

c# - 证书的 iOS 推送通知 AuthenticationException

android - 限制 android GCM 中的 collapse_key 计数。第2部分

node.js - 无效的配置对象。 Webpack 已使用与 Angular V4.0.0 中的 API 模式 2 不匹配的配置对象进行初始化

javascript - 我如何在 dynamicHepler 中渲染一个部分?

android - 如何通过蓝牙连接从 Android 应用程序在 Raspberry Pi 上运行脚本

firebase - 即使应用程序在 flutter 中被杀死,如何将用户位置发送到 Firestore?

.NET "Push"技术?