我需要在添加到firebase数据库之后发送推送通知我该怎么做

时间:2017-07-27 10:11:17

标签: node.js firebase firebase-realtime-database

https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html

我已经完成了上述博客。

下面用于在firebase中创建数据库的代码:

public static void sendNotificationToUser(String user, final String message) {
        DatabaseReference ref;
        ref = FirebaseDatabase.getInstance().getReference();
        final DatabaseReference notifications = ref.child("notificationRequests");

        Map notification = new HashMap<>();
        notification.put("username", user);
        notification.put("message", message);

        notifications.push().setValue(notification);
    }

这是我的index.js脚本代码:

var firebase = require('firebase-admin');
var request = require('request');

var API_KEY = ".AAAA6J9B3gg:APA91bEw_oHJSrAFuRxB6k6TzJ6wU-yzEw64yaf7CwBq7ur2iroGqi7Cf5JZ127wW_sBFtfdtBkpz15pPTVdQtkGPoMf6uBTMgq5AdTwXVWUDhtxQiGx5Pkj2CIpPDi0xTNT_ZMiEmIG";

var serviceAccount = require("path/to/serviceAccountKey.json");

firebase.initializeApp({
    credential: firebase.credential.cert(serviceAccount),
    databaseURL: "https://chitchatapp-73060.firebaseio.com/"
});
ref = firebase.database().ref();

function listenForNotificationRequests() {
    var requests = ref.child('notificationRequests');
    requests.on('child_added', function (requestSnapshot) {
        var request = requestSnapshot.val();
        sendNotificationToUser(
            request.username,
            request.message,
            function () {
                requestSnapshot.ref.remove();
            }
        );
    }, function (error) {
        console.error(error);
    });
};

function sendNotificationToUser(username, message, onSuccess) {
    request({
        url: 'https://fcm.googleapis.com/fcm/send',
        method: 'POST',
        headers: {
            'Content-Type': ' application/json',
            'Authorization': 'key=' + API_KEY
        },
        body: JSON.stringify({
            notification: {
                title: message
            },
            to: '/topics/user_' + username
        })
    }, function (error, response, body) {
        if (error) { console.error(error); }
        else if (response.statusCode >= 400) {
            console.error('HTTP Error: ' + response.statusCode + ' - ' + response.statusMessage);
        }
        else {
            onSuccess();
        }
    });
}
listenForNotificationRequests();

当我尝试部署它时,会出现如下错误:

  

解析触发器时出错:无法找到模块&#39;请求&#39;

1 个答案:

答案 0 :(得分:1)

您是否安装了请求模块?

npm install request

Npm install documentation.