【问题标题】:firebase functions running twicefirebase 函数运行两次
【发布时间】:2021-06-29 20:32:33
【问题描述】:

我正在使用来自 firebase 的函数和托管。

我已经定义了一个函数,如下所示。

const functions = require("firebase-functions")
const cors = require('cors')

exports.hello = functions.https.onRequest((request, response) => {
  functions.logger.info("Hello logs!", {structuredData: true})
  return cors()(request, response, () => {
    response.send({data: 'hello fire functions'})
  })
})

在托管中调用这样的函数:

import firebase from "firebase/app"
import "firebase/functions"

const config = { ... }
firebase.initializeApp( config )

const test = firebase.functions().httpsCallable('hello')

test().then( result => console.log(result) )

那么函数日志会被写入两次,如下:

2:37:07.548 PM hello: Function execution started
2:37:07.599 PM hello: Hello logs!
2:37:07.600 PM hello: Function execution took 53 ms, finished with status code: 204

2:37:07.809 PM hello: Function execution started
2:37:07.816 PM hello: Hello logs!
2:37:07.817 PM hello: Function execution took 8 ms, finished with status code: 200

它也在使用图中显示两次。

这种行为意味着我必须支付两倍的使用量。这不正常。

如果cors没有被使用,日志和使用图会显示它只执行了一次。

但是如果你不使用cors:当你在浏览器中调用一个函数时,该函数被执行,但是浏览器得到一个CORS错误。

我该如何解决这个问题?我在官方文档中找不到解决方案。 (这是托管和功能部署后的问题。不是localhost环境。)

【问题讨论】:

    标签: firebase google-cloud-functions


    【解决方案1】:

    首先,您将客户端上的 HTTP 请求与可调用函数混合在一起。那不是你应该做的。请查看HTTP functionscallable functions 的文档以了解它们有何不同。如果您在客户端使用可调用 SDK,则应在后端使用可调用函数。

    其次,这是正常的预期行为。可调用函数在客户端和服务器之间使用 CORS。 CORS 客户端发出preflight request,这会导致第一个请求和第一个日志。然后,导致第二个请求和第二个日志的实际请求。使用 CORS 时无法避免这种情况 - 这就是协议的工作原理。

    另见:

    【讨论】:

    • 感谢您的帮助。如果我编写onCall 函数并从客户端使用httpsCallable() 调用它一次,则使用量计为2。并且无法更改。我的理解正确吗?
    • 是的,这就是 CORS 的工作方式。
    【解决方案2】:

    如果您使用 Firebase 托管,则可能不需要 CORS。
    您可以通过向 firebase.json 添加重写来避免预检请求。
    但是有条件,比如函数的位置必须是us-central1。 https://firebase.google.com/docs/hosting/functions

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 1970-01-01
      • 2015-07-06
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多