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

Flutter Web部署Firebase Hosting遇FormatException错误求助

Flutter Web部署Firebase Hosting时JSON解析错误问题

问题现象

上传Flutter Web应用到Firebase Hosting时,控制台触发以下错误:

Rejecting promise with error: FormatException: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
  • 仅使用flutter build web生成的index.html时出现该问题,替换其他HTML文件可正常运行
  • 本地服务器(含Python搭建的服务器)运行完全正常
  • 已按Firebase和Flutter官方文档操作,甚至重建项目,问题仍未解决

生成的index.html代码

<!DOCTYPE html>
<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.

    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.

    For more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

    This is a placeholder for base href that will be replaced by the value of
    the `--base-href` argument provided to `flutter build`.
  -->
  <base href="/">

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="solUapp">

  <!-- Favicon 
  <link rel="icon" type="image/png" href="favicon.png"/>-->

  <title>solUapp</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <script src="flutter_bootstrap.js" async></script>

</body>
</html>

排查与解决方法

  1. 配置Firebase Hosting重写规则
    错误本质是Flutter路由跳转时,Firebase返回了404 HTML页面,前端误将其当作JSON解析。需在firebase.json中添加单页应用路由重写:

    {
      "hosting": {
        "public": "build/web",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ],
        "rewrites": [
          {
            "source": "**",
            "destination": "/index.html"
          }
        ]
      }
    }
    
  2. 验证构建与部署路径

    • 确认firebase.json中public字段指向Flutter构建产物目录build/web
    • 检查build/web下的flutter_bootstrap.js、manifest.json等资源是否完整,路径无错误
  3. 修正base href配置
    若应用部署在非根路径,构建时需指定--base-href参数:

    flutter build web --base-href "/你的子路径/"
    

    确保生成的index.html中<base href="...">值与部署路径一致,避免资源加载失败返回错误页

  4. 强制清除Firebase缓存
    部署后缓存可能导致旧资源残留,执行命令强制刷新:

    firebase deploy --only hosting:main --force
    

内容的提问来源于stack exchange,提问作者Mauricio Jiménez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:04:55