节点JS上的Firebase身份验证失败:NotAuthorizedError

时间:2016-12-15 01:18:05

标签: javascript node.js heroku firebase firebase-cloud-messaging

我正在尝试通过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没有正确初始化,但我已多次检查链接和密钥。我做错了什么?

1 个答案:

答案 0 :(得分:4)

在您的代码中,我注意到了这一部分(特别是评论):

// Planet Firebase API Key
var API_KEY = "AIz..."; // found at Project Settings > General > Web API Key
var fcm = new FCM(API_KEY);

您可能正在收到401 - Authentication Error

使用FCM时,您应始终使用服务器密钥而不是Web API密钥。
这在Firebase Console中也可见: 项目设置> 云消息传递>服务器密钥。

查看我的回答here,了解不同的密钥。