首页 > 解决方案 > firebase 函数运行两次

问题描述

我正在使用来自 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环境。)

标签: firebasegoogle-cloud-functions

解决方案


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


推荐阅读