firebase - 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环境。)
解决方案
如果您使用的是 Firebase 托管,则可能不需要 CORS。
您可以通过向 firebase.json 添加重写来避免预检请求。
但是有条件,比如函数的位置必须是us-central1。
https://firebase.google.com/docs/hosting/functions
推荐阅读
- snowflake-cloud-data-platform - Snowflake 是否向 DataGrip 等 SQL 客户端提供解释计划中的成本信息?
- windows - 使用 Powershell 进行网络安装修补程序
- python - 在这种情况下如何避免多次写入 csv 标头?
- django - Django:非主键自动递增字段
- ruby-on-rails - 无法在 Ruby on Rails 中抓取 Linkdin 搜索结果?
- android - viewpager2 的视图绑定错误
- html - 背景随着任何额外的位置、大小等代码消失,但在没有的情况下可见
- crystal-lang - Crystal 类中的 < 符号是做什么用的?
- android - Android中的平均堆栈环境
- python - 无法安装 django,我收到 JWT 错误