如何在 node.js 中集成 FCM 以进行推送通知? [英] How to integrate FCM in node.js for push notifications?

查看:53
本文介绍了如何在 node.js 中集成 FCM 以进行推送通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add the push notification thing using FCM in Node.js .For that I tried this

这个也是这个

我的 nodejs 代码

My nodejs code

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

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

Whenever I try to run this code and start my server,I get this error in the console always.

 /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)

谁能解释一下我做错了什么?

Can anybody please explain what I'm doing wrong?

推荐答案

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

I used the firebase-admin package for sending the notifications (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)
    })

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

The firebase-adminSDK.json can be download following the steps in https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app

此代码将向主题topic"发送通知,但是,firebase-admin 包允许向特定设备发送通知.

This code will send a notification to the topic 'topic', however, the firebase-admin package allows sending notifications to a specific device.

这篇关于如何在 node.js 中集成 FCM 以进行推送通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆