onCall 云函数返回“数据无法以 JSON 形式编码。南'

inv*_*vrt 4 javascript node.js firebase google-cloud-functions google-cloud-firestore

我有一个看起来像这样的 onCall 函数..

exports.getResults = functions.https.onCall((data, context) => {
  const admin = context.auth.token.admin
  const uniqueId = context.auth.uid
  const doc = db.collection('collection').doc(data.docId)

    return doc
      .get()
      .then(querySnapshot => {
        return querySnapshot.docs.map(doc => {
          const doc = doc.data()
          const collectionDoc = {
            docValues
          }
    
          return collectionDoc
        })
      })
      
Run Code Online (Sandbox Code Playgroud)

我的 console.log 将我请求的文档打印为对象,所以我不确定问题是什么?

小智 6

我了解到您在 Firebase 功能日志中遇到此错误。这意味着您正在返回NaN对象中的某个位置。根据这篇文章:

要将数据发送回客户端,请返回可以 JSON 编码的数据。

它可能取决于实现,但是这里NaN不能进行 JSON 编码。(在维基百科- 数据类型和语法 - 数字中找到了相关内容)。

您可以通过部署未初始化变量的函数来轻松复制此问题:

exports.getResults = functions.https.onCall(() => {
        var number;
        var value = number+1;
        return {
                value,
                "text": "test",
        };
})
Run Code Online (Sandbox Code Playgroud)

在示例中,我添加undefined到数字,结果将是NaN。当然,可能还有其他函数也会返回NaN。无论如何,如果您部署上面的示例,它将记录相同的错误“数据无法以 JSON.NaN 进行编码”。我认为这在代码中最容易被忽视。

我认为您必须仔细检查您返回的所有数据。