我是Firebase和nodejs的新手。我正在尝试使用Firebase云功能从一台设备向另一台设备发送通知。
这是发送通知的node.js代码:
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/sendNotification/{notificationId}')
.onWrite(event => {
var regToken="fYRweeL8cic:APA91bH6Q_gyKKrLL...";
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = event.data;
var payload = {
data: {
title: eventSnapshot.child("title").val()
}
};
// Set the message as high priority and have it expire after 24 hours.
var options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
admin.messaging().sendToDevice(regToken,payload,options)
.then(function(response){
console.log("Successfully sent message: ", response);
})
.catch(function(error){
console.log("Error sending message: ", error);
})
})
这是将通知添加到实时数据库以触发功能的代码:
public void sendNotification(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("sendNotification");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(getApplicationContext(),
"sent", Toast.LENGTH_SHORT).show();
Map data = new HashMap();
data.put("title", "this is my title");
data.put("message", "this is the message");
myRef.push().setValue(data);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
我可以看到该函数已执行,但出现以下错误:
这是该功能在控制台中的显示方式:
问题是未发送通知。
我得到了这个:{results:[{error: [Object]}]
出于某种原因。
造成这种错误的原因是什么?
编辑:(解决方案)
正如评论中所建议的,我使用了这个:JSON.stringify(response)
来获取更多信息。这是回应:
{"results":[{"error":{"code":"messaging/registration-token-not-registered","message":"The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages."}}],"canonicalRegistrationTokenCount":0,"failureCount":1,"successCount":0,"multicastId":6051985890611026000}
响应非常明确,令牌已经改变。我已将其更改为有效令牌并且有效。
答案 0 :(得分:4)
正如评论中所建议的,我使用了这个:JSON.stringify(response)
来获取更多信息。这是回应:
{"results":[{"error":{"code":"messaging/registration-token-not-registered","message":"The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages."}}],"canonicalRegistrationTokenCount":0,"failureCount":1,"successCount":0,"multicastId":6051985890611026000}
响应非常明确,令牌已经改变。我已将其更改为有效令牌并且有效。