云函数: 详细堆栈跟踪: 错误: 找不到模块'fcm-push'



我正在尝试创建一个函数,该函数在获取设备令牌后向设备发送推送通知。函数已正确部署,但函数在日志中出现错误。正如我在下面提到的,错误是

cannot find module fcm push 

我试过了:-

$ install npm fcm-push
$ install npm fcm-push --save

这不会改变错误。

函数通知收到此错误:-

{"@type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function load error: Code in file index.js can't be loaded.nDid you list all required modules in the package.json dependencies?nDetailed stack trace: Error: Cannot find module 'fcm-push'n    at Function.Module._resolveFilename (module.js:476:15)n    at Function.Module._load (module.js:424:25)n    at Module.require (module.js:504:17)n    at require (internal/module.js:20:19)n    at Object.<anonymous> (/user_code/index.js:5:13)n    at Module._compile (module.js:577:32)n    at Object.Module._extensions..js (module.js:586:10)n    at Module.load (module.js:494:32)n    at tryModuleLoad (module.js:453:12)n    at Function.Module._load (module.js:445:3)"},"authenticationInfo":{"principalEmail":"muddasar.pixster@gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction","resourceName":"projects/testingproject-80016/locations/us-central1/functions/Notificaation"}

我也明白这个

Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'fcm-push'
at Function.Module._resolveFilename (module.js:476:15)
at Function.Module._load (module.js:424:25)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/index.js:5:13)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)

我的包.json 是

{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.0.3"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0"
},
"private": true
}

我的代码是

'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.Notificaation = functions.firestore.document("Token/{token_id}").onWrite((change, context) => {

console.log('Toekn id', context.params.token_id);
const req = context.params.token_id;
return admin.firestore().collection('UseData').doc(id).get()
.then(snapshot => {
const uid=snapshot.data().user_id;
console.log("User id: ", uid);

return admin.firestore().collection('UserData').doc(uid).collection('Token').doc(req).get()
.then(snap=>
{

if(uid === null)
{
console.log("You are not logged in");
}
else
{
return admin.firestore().collection('UserData').doc(uid).collection('Join_members').get()
.then(snap=>
{
snap.forEach(doc =>{
return admin.firestore().collection("Token").doc(doc.data().user).get()
.then(snapshot2 =>
{
const tid2=snapshot2.data().token_id;
console.log(" Token_id: ",tid2);

const payload2= {
notification:{
title:"Notification",
body:"New Message.",

},
data:
{
user_id:id,
message:'1',
}
};
console.log(payload2);
const options = {
priority: "high",
timeToLive: 60 * 60 *24,
content_available: true,
};


return admin.messaging().sendToDevice(tid2, payload2,options).then(result => {
var db = admin.firestore();
var data = {
type:'New Message Arrived',
status:1,
timestamp:admin.firestore.FieldValue.serverTimestamp()
};
var data1 = {
notifiction_message:0
};

var setDoc = db.collection('UserData').doc(doc.data().user).collection('notification').doc().set(data);
var setDoc1 = db.collection('UserData').doc(doc.data().user).update(data1);
return console.log('Notify when New Message ');
});
});
});
console.log("Sucess");
return true;
});
}
return true;
});
});
});

您可能需要将其添加到依赖项中(相当于本地npm install fcm-push(:

"dependencies": {
...
"fcm-push": "1.1.3"
},

然后在代码中要求它:

var FCM = require('fcm-push');

您不需要在云函数中使用fcm-push模块。

云功能将仅用于发送通知。

为了获取客户端设备的 FCM 令牌,您应该在客户端实现特定代码。

请参阅以下官方 Firebase 示例,其中实现了此类机制:https://github.com/firebase/functions-samples/tree/master/fcm-notifications(节点 6 的版本(。

请查看以下 JS 文件,其中发送令牌的逻辑在第 184 行到 211 行实现。代码粘贴在下面以供将来参考。

在此示例中,当用户获得新的关注者时,将触发通知发送(请参阅索引.js云函数文件(:

exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}')
.onWrite((change, context) => {})

由于您已(在评论中(表示要"向登录我的应用的用户"发送通知,因此您应该创建自己的触发器机制,因为没有现成的用户登录触发器,请参阅适用于 Firebase 的 Cloud Functions 是否可以在用户登录时执行?。


令牌发送的示例代码摘录:

// Saves the token to the database if available. If not request permissions.
Demo.prototype.saveToken = function() {
firebase.messaging().getToken().then(function(currentToken) {
if (currentToken) {
firebase.database().ref('users/' + this.currentUid + '/notificationTokens/' + currentToken).set(true);
} else {
this.requestPermission();
}
}.bind(this)).catch(function(err) {
console.error('Unable to get messaging token.', err);
if (err.code === 'messaging/permission-default') {
this.fcmErrorContainer.innerText = 'You have not enabled notifications on this browser. To enable notifications reload the page and allow notifications using the permission dialog.';
} else if (err.code === 'messaging/notifications-blocked') {
this.fcmErrorContainer.innerHTML = 'You have blocked notifications on this browser. To enable notifications follow these instructions: <a href="https://support.google.com/chrome/answer/114662?visit_id=1-636150657126357237-2267048771&rd=1&co=GENIE.Platform%3DAndroid&oco=1">Android Chrome Instructions</a><a href="https://support.google.com/chrome/answer/6148059">Desktop Chrome Instructions</a>';
}
}.bind(this));
};
// Requests permission to send notifications on this browser.
Demo.prototype.requestPermission = function() {
console.log('Requesting permission...');
firebase.messaging().requestPermission().then(function() {
console.log('Notification permission granted.');
this.saveToken();
}.bind(this)).catch(function(err) {
console.error('Unable to get permission to notify.', err);
});
};

最新更新