【问题标题】:Error 500 in Firebase functions during Like & Dislike feature喜欢和不喜欢功能期间 Firebase 函数中的错误 500
【发布时间】:2019-06-07 18:57:54
【问题描述】:

我目前正在看一个从udemy买的教程,在实施过程中,我在实施Like or Dislike功能时遇到了问题。

当我向 Firebase 函数发出发布请求时,我在控制台中收到错误 500,并且在 Firebase 函数日志中看到此错误:

Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.
    at Object.validateResourcePath (/srv/node_modules/@google-cloud/firestore/build/src/path.js:403:15)
    at CollectionReference.doc (/srv/node_modules/@google-cloud/firestore/build/src/reference.js:1718:20)
    at exports.updateLikesCount.functions.https.onRequest (/srv/lib/index.js:24:44)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at /worker/worker.js:783:7
    at /worker/worker.js:766:11
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)

Firebase 的 Index.js 文件函数

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp(functions.config().firebase);


// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript


export const updateLikesCount = functions.https.onRequest((request, response) => {

    console.log(request.body);

    const eventId = request.body.eventId;
    const userId = request.body.userId;
    const state = request.body.state; //like or unlike

    // tslint:disable-next-line: no-floating-promises
    admin.firestore().collection("events").doc(eventId).get().then((data: any) => {

        let likesCount = data.data().likesCount || 0;
        let likes = data.data().likes || [];

        let updateData = {} as any;


        if (state === "like") {
            updateData["likesCount"] = ++likesCount;
            updateData[`likes.${userId}`] = true;
        }
        else {
            updateData["likesCount"] = --likesCount;
            updateData[`likes.${userId}`] = false;
        }

        admin.firestore().collection("events").doc(eventId).update(updateData).then(() => {
            response.status(200).send("Done");
        }).catch((err) => {
            response.status(err.code).send(err.message);
        })

    }).catch((err) => {
        response.status(err.code).send(err.message);
    })
})

Feed.html

<div class = "content" *ngFor="let event of events">
<ion-button (click)="like(event)">Like</ion-button>
...

Feed.page.ts

like(event) {
    let body = {
      eventId: event.id,
      userId: firebase.auth().currentUser.uid,
      state: event.data().likes && event.data().likes[firebase.auth().currentUser.uid] == true ? "unlike" : "like",
    }

    // tslint:disable-next-line: max-line-length
    this.http.post("https://us-central1-cp-eventoo.cloudfunctions.net/updateLikesCount", JSON.stringify(body), { responseType: "text" }).subscribe((data) => { //third parameter represents the response(200) in functions
      console.log(data)
    }, (error) => {
      console.error(error.status);
    })
  }

当我点击喜欢按钮时,我得到错误 500,当我用邮递员测试时,我得到这个错误:

Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.
    at Object.validateResourcePath (/srv/node_modules/@google-cloud/firestore/build/src/path.js:403:15)
    at CollectionReference.doc (/srv/node_modules/@google-cloud/firestore/build/src/reference.js:1718:20)
    at exports.updateLikesCount.functions.https.onRequest (/srv/lib/index.js:24:44)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at /worker/worker.js:783:7
    at /worker/worker.js:766:11
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)

【问题讨论】:

  • 您确定['likes.${userId}'] 不应该是["likes.${userId}"](括号错误)吗?

标签: javascript angular firebase ionic-framework ionic4


【解决方案1】:
if (typeof (request.body) === 'string') {
        body = JSON.parse(request.body);
    } else {
        body = request.body;
    }

通过添加这些代码行,问题就解决了。谢谢!

【讨论】:

  • 继续粉碎它
【解决方案2】:
if (!is.string(resourcePath) || resourcePath === '') {
  throw new Error(`Path must be a non-empty string.`);
}

这对你来说是失败的,你的邮递员原始数据需要是 JSON 格式。默认设置为文本,必须改为JSON(application/json)

另外,确保你的函数返回一个承诺

export const updateLikesCount = functions.https.onRequest((request, response) => {

    console.log(request.body);

    const eventId = request.body.eventId;
    const userId = request.body.userId;
    const state = request.body.state; //like or unlike

    return admin.firestore().collection("events").doc(eventId).get().then((data: any) => {

        let likesCount = data.data().likesCount || 0;
        let likes = data.data().likes || [];

        let updateData = {} as any;


        if (state === "like") {
            updateData["likesCount"] = ++likesCount;
            updateData[`likes.${userId}`] = true;
        }
        else {
            updateData["likesCount"] = --likesCount;
            updateData[`likes.${userId}`] = false;
        }


 return admin.firestore().collection("events").doc(`${eventId}`).update(updateData).then(() => {
            response.status(200).send("Done");
        }).catch((err) => {
            response.status(err.code).send(err.message);
        })

    }).catch((err) => {
        response.status(err.code).send(err.message);
    })
})

我为您的函数添加了几个返回语句,知道何时完成,同时确保文档使用 eventId 作为字符串。

最后,我不需要JSON.stringify(body) 你的有效载荷,按原样发送对象;完全没问题。

【讨论】:

  • 我添加了返回但相同。另外 if (!is.string(resourcePath) || resourcePath === '') { throw new Error(Path must be a non-empty string.);我不明白把这行代码放在哪里。如果我删除 JSON.Stringify 则存在与 CORS 相关的错误
猜你喜欢
  • 2018-06-26
  • 2021-07-10
  • 1970-01-01
  • 2018-05-27
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多