简体   繁体   English

Firebase 错误:Function 加载用户代码失败(node.js)

[英]Firebase error: Function failed on loading user code (node.js)

I am a relative noob with Firebase my first time using it and following along with a tutorial.我是 Firebase 的相对菜鸟,这是我第一次使用它并遵循教程。 The tutorial is a bit outdated and I have been fixing bugs as I have been going, but this one has got me completely stuck.该教程有点过时,我一直在修复错误,但是这个让我完全陷入困境。 I try to run a different functions that trigger when a document is created in certain collections. However, i get the following error:我尝试运行在某些 collections 中创建文档时触发的不同函数。但是,我收到以下错误:

Error错误

!  functions[createNotificationOnlike(us-central1)]: Deployment error.
Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs

There are 3 more identical errors that correspond to the other exports in the following index.js file.还有 3 个相同的错误对应于以下 index.js 文件中的其他导出。

Index.js索引.js

exports.createNotificationOnlike = functions.firestore.document('likes/{id}').onCreate(async (snapshot) => {
    try {
        const doc = await db.doc(`posts/${snapshot.data().postId}`).get(); // we have access to user handle via the likes route
        if(doc.exists){
            await db.doc(`notifications/${snapshot.id}`).set({ // the id of the like is the same as the id of the notification that pertains to the like
                createdAt: new Date().toISOString,
                recipient: doc.data.userHandle,
                sender: snapshot.data().userHandle,
                type: 'like',
                read: false,
                postId: doc.id
            });
            return;
        }    
    } catch (err) {
        console.error(err);
        return;
    }
});

exports.removeNotificationOnUnlikePost = functions.firestore.document('likes/{id}').onDelete( async (snapshot) => {
    try {
        await db.doc(`notifications/${snapshot.id}`).delete();
        return;   
    } catch (err) {
        console.error(err);
        return;
    }
})

exports.createNotificationForComments = functions.firestore.document('comments/{id}').onCreate(async (snapshot) => {
    try {
        const doc = await db.doc(`posts/${snapshot.data().postId}`).get();
        if(doc.exists){
            db.doc(`notifications/${snapshot.id}`).set({
                createdAt: new Date().toISOString,
                recipient: doc.data.userHandle,
                sender: snapshot.data().userHandle,
                type: 'comment',
                read: false,
                postId: doc.id
            })
            return;
        }
    } catch (err) {
        console.error(err);
        return; // we dont need return messages since this isnt an endpoint it is a db trigger event
    }
})

// auto turn the app into base route url/api
exports.api = functions.https.onRequest(app);

I have checked the logs as suggested by the error and i get the following messages which i think are useless, there are three other identical errors for the other functions我已经按照错误的建议检查了日志,我收到了以下我认为无用的消息,其他功能还有其他三个相同的错误

Error Logs错误日志

removeNotificationOnUnlikePost
{"@type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs"}

Here is my package.json file这是我的 package.json 文件

Package.json Package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "10"
  },
  "dependencies": {
    "busboy": "^0.3.1",
    "express": "^4.17.1",
    "firebase": "^7.16.0",
    "firebase-admin": "^8.10.0",
    "firebase-functions": "^3.6.1"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

Lastly, here is my config stuff that was used to initialize everything:最后,这是我用于初始化所有内容的配置内容:

admin.js管理员.js

const admin = require('firebase-admin');
var serviceAccount = require('../../service-acct/socialapp-e5130-firebase-adminsdk-uo6p6-5495e18b97.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    storageBucket: "socialapp-e5130.appspot.com",
    databaseURL: "https://socialapp-e5130.firebaseio.com"
});

const db = admin.firestore();

module.exports = { db, admin }

Firebase init Firebase 初始化

const firebase = require('firebase');
const config  = require('../util/config.js');
firebase.initializeApp(config);

PS It is worth mentioning that the http.onRequest trigger (api) was actually working and I have been developing without deploying using firebase serve. PS 值得一提的是 http.onRequest 触发器 (api) 实际上在工作,我一直在开发而不使用 firebase 服务进行部署。 Now that I am ready to deploy these triggers something is going heinously wrong.现在我已准备好部署这些触发器,但出现了令人发指的错误。 Any help is greatly appreciated任何帮助是极大的赞赏

Enter this command for getting log:输入此命令以获取日志:

firebase functions:log

I had the exact same problem, trying to deploy the exact same code as you and I was just able to get it to deploy properly.我遇到了完全相同的问题,尝试部署与您完全相同的代码,而我只是能够正确部署它。

If yours is the same issue as mine, this is where the problem is:如果您的问题与我的问题相同,则问题出在:

var serviceAccount = require('../../service-acct/socialapp-e5130-firebase-adminsdk-uo6p6-5495e18b97.json');

It looks like when deploying to firebase you cant have code trying to reach outside your project folder, so the solution would be to have the key inside which isn't recommended or to set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of your service account key json file as explained in https://firebase.google.com/docs/admin/setup#windows and then just having看起来在部署到 firebase 时,您无法让代码尝试到达项目文件夹之外,因此解决方案是使用不推荐的密钥或将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为服务帐户密钥的文件路径json 文件,如https://firebase.google.com/docs/admin/setup#windows中所述,然后只需

admin.initializeApp();

I had this error once and I fixed it by checking my code again, check maybe you require or import a dependency or module that you have not installed and try to check your package.json file make sure you installed all the necessary module and dependencies.我曾经遇到过这个错误,我通过再次检查我的代码来修复它,检查您是否需要或导入尚未安装的依赖项或模块,并尝试检查您的 package.json 文件,确保您安装了所有必要的模块和依赖项。

But mostly the problem is due to importing a module you did not install or there is a bug in your code但大多数问题是由于导入了您未安装的模块或代码中存在错误

in my case i had a file starting with capital case letter, but require(...) with a lower case letter, it worked on Mac because it ignores it, as i understand, but deploying these functions results in this error.在我的情况下,我有一个以大写字母开头的文件,但 require(...) 以小写字母开头,它可以在 Mac 上运行,因为据我所知,它会忽略它,但是部署这些函数会导致此错误。

Renaming file to lower case fixed this error for me.将文件重命名为小写为我解决了这个错误。

With the suggestion of the recommended answer I moved all my cloud functions code to the single index.js file (rather than 'require' statements) and it seemed to work for me.根据推荐答案的建议,我将所有云函数代码移至单个 index.js 文件(而不是“要求”语句),它似乎对我有用。 Note that I omitted any API keys and such and it still worked.请注意,我省略了任何 API 键等,它仍然有效。 I am assuming that since this deployment is handled by the firebase CLI it already knows this is a trusted environment.我假设由于此部署由 firebase CLI 处理,因此它已经知道这是一个受信任的环境。

I had the same issue while setting up SendGrid.我在设置 SendGrid 时遇到了同样的问题。

I got this error because I accidentally installed SendGrid to the root folder instead of the functions folder.我收到此错误是因为我不小心将 SendGrid 安装到了根文件夹而不是函数文件夹。

Make sure to install your service to your functions folder using the cmd prompt.确保使用 cmd 提示符将您的服务安装到您的函数文件夹。 It should look something like this: D:\firebaseProject\functions> npm i @sendgrid/mail它应该看起来像这样:D:\firebaseProject\functions> npm i @sendgrid/mail

Mine was because I tried to import a module that dependents that is not standard-alone我的是因为我试图导入一个依赖于非标准的模块

const axioms = require("axioms");

I solved it by adding the module name version to dependencies list in the package.json file.我通过将模块名称版本添加到 package.json 文件中的依赖项列表来解决它。

"dependencies": {
    ....
    "axios": "^0.27.2"
}

I got the module version with this command我用这个命令得到了模块版本

npm view axios version

I had this same problem.我有同样的问题。 check if your package.json file has all the dependencies that you used to write firebase functions.检查您的 package.json 文件是否具有您用于编写 firebase 函数的所有依赖项。

eg I had written a firebase function in which I called nodemailer dependancy but did not installed in package.json file of 'functions' directory例如,我写了一个 firebase function,其中我调用了 nodemailer dependancy,但没有安装在“函数”目录的 package.json 文件中

Note: Remember to install required packages in 'functions' directory only注意:请记住仅在“功能”目录中安装所需的包

Another way to view deployment-time logs is to go to the Logs Explorer in the Google Cloud Console.另一种查看部署时日志的方法是拨打 go 到 Google Cloud Console 中的日志资源管理器。

If you're not familiar with Google Cloud console, maybe because you're only familiar with the Firebase console that's a simplified version of the Google Cloud console, then check out these docs for how to access the Logs Explorer on Google Cloud Console .如果您不熟悉 Google Cloud 控制台,可能是因为您只熟悉 Firebase 控制台,它是 Google Cloud 控制台的简化版本,请查看这些文档以了解如何在 Google Cloud Console 上访问日志资源管理器

In my case, I had to access the logs from the Logs Explorer because when I ran firebase functions:log as suggested by Chinmay Atrawalkar, I got the error Error: Failed to list log entries Failed to retrieve log entries from Google Cloud.就我而言,我必须从日志资源管理器访问日志,因为当我按照 Chinmay Atrawalkar 的建议运行firebase functions:log时,我收到错误Error: Failed to list log entries Failed to retrieve log entries from Google Cloud. . .

Through the Logs Explorer, I could see the following error: Detailed stack trace: Error: Cannot find module 'file-saver' .通过日志资源管理器,我可以看到以下错误: Detailed stack trace: Error: Cannot find module 'file-saver' From there I was able to figure out I just needed to add file-saver to my functions/package.json dependencies by running yarn add file-saver from my functions directory.从那里我能够弄清楚我只需要通过从我的函数目录运行yarn add file-saver来将file-saver添加到我的 functions/package.json 依赖项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 云函数部署错误:加载用户代码时函数失败。 错误信息:无法加载文件 lib/index.js 中的代码 - Cloud functions deployment error: Function failed on loading user code. Error message: Code in file lib/index.js can't be loaded 使用 node.js 部署 firebase 时出现错误 - Getting an error when deploying firebase with node.js 如何将 Firebase 连接到 Node.JS 项目? - How to connect Firebase to a Node.JS project? Firebase 存储 | 从 node.js 云函数上传时文件是“application/octet-stream” - Firebase Storage | File is "application/octet-stream" on upload from node.js cloud function 如何使用 Node.js 和“firebase-admin”SDK 查询 Firebase? - How to query Firebase with Node.js and "firebase-admin" SDK? 如何使用 Node.js 上的 blob 将图像存储在 firebase 存储上 - How to store image on firebase storage with blob on Node.js 找不到 package.json。 Node.js 可能有启动问题。 验证 package.json 是否有效或将代码放在名为 server.js 或 app.js 的文件中 - Failed to find package.json. Node.js may have issues starting. Verify package.json is valid or place code in a file named server.js or app.js 尝试使用 node.js Lambda 函数在 AWS REST API 配置上使用 Axios 发布数据时出现 CORS 错误 - CORS error while trying to post data with Axios on AWS REST API configuration using a node.js Lambda function Firebase Function 无法从源加载 function 定义错误解决方案 - Firebase Function Failed to load function definition from source error Solution 从 Node js 调用 Flutter web 应用程序 function ZBF12E1515C25C7D8A15AB2F14Z13 - Call Flutter web app from Node js function firebase
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM