firebase - 是否可以在 Firebase Hosting 重写中缓存 Cloud Function 调用结果,而与请求的 URL 无关?

标签 firebase google-cloud-functions firebase-hosting

我正在将 Firebase 托管中的多个路径重写为始终返回相同结果的云函数。我需要调用该函数一次,缓存其结果,并将其返回以供对任何这些路径的任何后续请求。然而,正如documentation states ,缓存内容的提供基于:

  • The hostname
  • The path
  • The query string
  • The content of the request headers specified in the Vary header

因此,如果请求不同的 URL,该函数将被再次调用。但有办法避免这种情况吗?设置 Cache-Control header 确实可以防止该函数在请求相同 URL 时再次调用,但在请求不同 URL 时则不会。


这是我的托管和功能配置:

firebase.json:

{
  "hosting": {
    "rewrites": [
      {
        "source": "**",
        "function": "myFunction"
      }
    ]
  }
}

functions/index.ts:

import * as functions from "firebase-functions"

export const myFunction = functions.https.onRequest((req, res) => {
    res.set("Cache-Control", "public, max-age=31536000")
    res.send("This is a Cloud Function.")
})

最佳答案

Firebase 托管(和网络浏览器)的缓存行为始终取决于 URL 路径。

根据您的目标,您可以尝试通过多种方法来解决此问题:

  1. 使用重定向(例如,重定向到 /)而不是重写。然后,云功能只能在已知(且可缓存)路径上提供内容。
  2. 在每个路径上提供静态页面而不是云函数,然后让该静态页面使用 JavaScript 在已知的缓存路径上调用云函数。初始静态页面不会被缓存,但它应该比函数更快。

关于firebase - 是否可以在 Firebase Hosting 重写中缓存 Cloud Function 调用结果,而与请求的 URL 无关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62950265/

相关文章:

Firebase 远程配置 getInt() 丢失

ios - 从 firebase 中获取 UI Image 与在 .text 中获取 UI Label 有何不同,图像获取会产生哪些潜在问题?

javascript - Firebase:如何在 HTTP 函数下动态包含模块

javascript - Firebase http 路由不起作用

javascript - Firebase 函数不返回 set-cookies header

firebase - 使用 Geofire + Firebase 过滤结果

firebase - 内容未使用 firebaseserve 更新——仅托管

firebase - 如何配置 Ionic 3 Firebase 分析

android - 如何将设备连接到我的 Android firebase 数据库

android - Firebase 计划为 strip 集成付款