You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web:Firestore调试模式正常,发布构建后无法更新数据

Firestore更新功能发布服务器后失效的解决方案

问题情况

Firestore数据更新功能在移动端和Web调试模式下正常运行,但发布到生产服务器后完全失效。

相关代码

index.html中的Firebase初始化代码

<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.3/firebase-app.js";
  import { getFirestore, collection, getDocs } from 'https://www.gstatic.com/firebasejs/9.9.3/firebase-firestore.js';
  // TODO: Add SDKs for Firebase products that you want to use
  
  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: -----,
    authDomain: ------,
    projectId: ------,
    storageBucket: ------,
    messagingSenderId: ------,
    appId: ------,
    measurementId: ------
  };
  
  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const db = getFirestore(app);
</script>

Firestore更新代码(Flutter)

FirebaseFirestore.instance
    .collection('orderDetails')
    .doc(id)
    .update({
  'status': status,
}).catchError((e) {
  print(e);
});

浏览器控制台报错(翻译后)

拒绝加载脚本'https://www.gstatic.com/firebasejs/9.9.3/firebase-app.js',因为它违反了以下内容安全策略指令:"script-src 'self' 'unsafe-inline' 'unsafe-eval' http://myserverurl.com https://myserverurl.com http://www.myserverurl.com https://www.myserverurl.com"。注意'script-src-elem'未明确设置,因此使用'script-src'作为回退。

VM86:3 未捕获(在 promise 中)TypeError:无法获取动态导入的模块:https://www.gstatic.com/firebasejs/9.9.0/firebase-app.js

问题原因

服务器配置的内容安全策略(CSP) 未允许从https://www.gstatic.com域名加载脚本,导致Firebase核心JS模块无法正常加载,Firebase初始化失败后,后续的Firestore更新操作自然无法执行。另外代码中导入的Firebase版本(9.9.3)与报错中出现的版本(9.9.0)不一致,也可能引发加载异常。

解决步骤

  1. 更新服务器CSP配置:在script-src指令中添加https://www.gstatic.com,允许加载该域名下的Firebase脚本。修改后的CSP指令示例:

    script-src 'self' 'unsafe-inline' 'unsafe-eval' http://myserverurl.com https://myserverurl.com http://www.myserverurl.com https://www.myserverurl.com https://www.gstatic.com
    

    具体修改方式取决于你的服务器类型(如Nginx、Apache或CDN配置),找到对应的CSP设置项添加该域名即可。

  2. 统一Firebase模块版本:确保所有导入的Firebase模块使用同一版本,避免版本不一致导致的加载失败。比如将所有导入的Firebase脚本版本统一为9.9.3,消除报错中出现的版本差异。

  3. 验证配置生效:修改完成后重新部署到服务器,通过浏览器开发者工具的「Security」面板查看当前生效的CSP规则,确认https://www.gstatic.com已被包含在script-src允许列表中。

内容的提问来源于stack exchange,提问作者eslam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:18:33