【发布时间】:2017-04-30 12:12:17
【问题描述】:
我正在尝试通过 Firebase/Node JS 发送推送通知。我目前在 Heroku 上运行此代码。
var Firebase = require('firebase');
var request = require('request');
var express = require('express');
var FCM = require('fcm-node');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/push', function(request, response) {
response.send("running");
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
// Planet Firebase API Key
var API_KEY = "AIz..."; // found at Project Settings > General > Web API Key
var fcm = new FCM(API_KEY);
var config = {
apiKey: "AIz...",
authDomain: "XXX.firebaseapp.com", // Authentication > Sign-In Method > OAuth Redirect Domains
databaseURL: "https://XXX.firebaseio.com/", // Database > Url at the top
storageBucket: "gs://XXX.appspot.com", // Storage > Url at the top
};
var firebase = Firebase.initializeApp(config);
var ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child('notifications');
requests.on('child_changed', function(requestSnapshot) {
var objectAdded = requestSnapshot.val();
var uid = receiver["uid"]
var notificationMessage = objectAdded["message"]
sendNotificationToUser(uid, notificationMessage);
}, function(error) {
console.error(error);
});
};
function sendNotificationToUser(receiverID, notificationMessage) {
var message = {
to: '/notifications/'+receiverID,
notification: {
title: "App Title",
body: notificationMessage,
badge: 1
}
};
fcm.send(message, function(err, response){
if (response) {
console.log("Successfully sent with response: ", response);
} else {
console.log("Something has gone wrong! Error: " + err);
}
});
}
// start listening
listenForNotificationRequests();
每当fcm.send() 被调用时,我都会返回:
Something has gone wrong! Error: NotAuthorizedError
这让人相信 Firebase 未正确初始化,但我已多次检查链接和密钥。我做错了什么?
【问题讨论】:
-
你有更详细的错误响应吗?
-
不幸的是,我没有。这就是它给我的一切。
-
你试过了吗?我的意思是我的回答。使用 Server Key 后是否可以发送消息?
标签: javascript node.js heroku firebase firebase-cloud-messaging