如何使用 Flutter Web 和 CanvasKit 渲染器配置 CORS?

发布于 2025-01-21 01:24:28 字数 3763 浏览 0 评论 0 原文

问题

我有一个托管在firebase托管的flutter Web项目,该项目托管了用Canvaskit渲染的,我无法加载其加载外部图像,该图像托管在Xano CDN或加载Googleplaces API结果(自动编译)中。 我阅读了许多其他解决方案(例如 this or 或 thisis ),但无行。我也在Google Cloud Cloud 上配置了CORS。

我的文件

这是我的 firebase.json file:

{
  "hosting": {
    "public": "build/web",
    "ignore": [
      "firebase.json",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "headers": [
      {
        "source": "*",
        "headers": [
          {
            "key": "Access-Control-Allow-Origin",
            "value": "*"
          }
        ]
      }
    ]
  }
}

了以下脚本:

<!-- Firebase -->
<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
  import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-analytics.js";
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = {
    apiKey: *mykey*,
    authDomain: "hearth-148b0.firebaseapp.com",
    projectId: "hearth-148b0",
    storageBucket: "hearth-148b0.appspot.com",
    messagingSenderId: *id*,
    appId: *myappid*,
    measurementId: *id*
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
</script>

在index.html中,我已经在&lt;/body&gt; tag之前附加 Cachednetworkimage中的标题:

return CachedNetworkImage(
    httpHeaders: {"Access-Control-Allow-Origin": "*"},
    imageUrl: imageUrl,
    fit: fit,
    width: width,
    height: height,
    progressIndicatorBuilder: (context, url, downloadProgress) =>
        LoadingPlaceholder(width: width),
    errorWidget: (context, url, error) => SizedBox(width: width),
  );

我尝试在Google Place Initializer中包括标题:

 final GooglePlace googlePlace = GooglePlace(
    kTokenGMaps,
    headers: {"Access-Control-Allow-Origin": "*"},
  );

错误

这些是我从浏览器控制台中获得的错误类型:

无法加载资源:net :: err_blocked_by_client

访问xmlhttprequest at 'https://storage.googleapis.com/xatr-ly1x-gkt1.n7.xano.io/vault/xhl5_hu1/fmpw0ycx/c01_ng../9de15de15d31/monemento_ai_ai_ai_caduti_caduti_caduti_in_in_in_in_corsososososososososososososososososososososososososososososososososososososososososososososososososososososososososososososo.coropa.jpa (从 'https://xatr-ly1x-gkt1.n7.xano.io/vault/xhl5_hu1/fmpw0ycx/c01_ng../monumento_ai_ai_ai_caduti_in_corso_corso_corso_europa.jeuropa.jpg? 从原点“ https://hearth-148b0.web.app”被CORS阻止 策略:没有“访问控制 - 允许孔”标头 请求的资源。

中部署

部署在Firebase上的命令

flutter build web
firebase deploy

从Android Studio:替代方案

这些是我用来

Header set Access-Control-Allow-Origin *

Problem

I have a Flutter Web project hosted on Firebase Hosting rendered with CanvasKit and I can't make it load external images hosted in a Xano CDN or load GooglePlaces API results (autocompiling).
I read many other solutions (like this or this or this) but none works. I also configured CORS on Google Cloud.

My files

This is my firebase.json file:

{
  "hosting": {
    "public": "build/web",
    "ignore": [
      "firebase.json",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "headers": [
      {
        "source": "*",
        "headers": [
          {
            "key": "Access-Control-Allow-Origin",
            "value": "*"
          }
        ]
      }
    ]
  }
}

In index.html I have appended the following script, right before the </body> tag:

<!-- Firebase -->
<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
  import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-analytics.js";
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = {
    apiKey: *mykey*,
    authDomain: "hearth-148b0.firebaseapp.com",
    projectId: "hearth-148b0",
    storageBucket: "hearth-148b0.appspot.com",
    messagingSenderId: *id*,
    appId: *myappid*,
    measurementId: *id*
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
</script>

I tried to include the header in the CachedNetworkImage:

return CachedNetworkImage(
    httpHeaders: {"Access-Control-Allow-Origin": "*"},
    imageUrl: imageUrl,
    fit: fit,
    width: width,
    height: height,
    progressIndicatorBuilder: (context, url, downloadProgress) =>
        LoadingPlaceholder(width: width),
    errorWidget: (context, url, error) => SizedBox(width: width),
  );

And I tried to include the headers in GooglePlace initializer:

 final GooglePlace googlePlace = GooglePlace(
    kTokenGMaps,
    headers: {"Access-Control-Allow-Origin": "*"},
  );

The errors

These are the type of errors I get from the browser console:

Failed to load resource: net::ERR_BLOCKED_BY_CLIENT

or

Access to XMLHttpRequest at
'https://storage.googleapis.com/xatr-ly1x-gkt1.n7.xano.io/vault/xhL5_hu1/fMPW0YCx/C01_Ng../9de15d31/Monumento_ai_caduti_in_Corso_Europa.jpg'
(redirected from
'https://xatr-ly1x-gkt1.n7.xano.io/vault/xhL5_hu1/fMPW0YCx/C01_Ng../Monumento_ai_caduti_in_Corso_Europa.jpg?tpl=big:box')
from origin 'https://hearth-148b0.web.app' has been blocked by CORS
policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.

Deploy

These are the commands I use to deploy on firebase, from android studio:

flutter build web
firebase deploy

Alternative

I also tried to use another host with FTP and setting the .htaccess file to:

Header set Access-Control-Allow-Origin *

but no success.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幸福%小乖 2025-01-28 01:24:28

我通过调整服务器端的CORS设置解决了这个问题。起初我以为是客户端的问题,后来发现是服务器配置错误造成的。

就我而言,我使用的是 Firebase Storage,并且必须在计算机上创建一个 cors.json 文件才能启用 CORS。我的配置如下:

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

详细说明:

  • "origin": ["*"] 允许来自任何来源的请求访问资源。您可以指定特定域或域列表来限制允许访问资源的源。

  • "method": ["GET"] 仅允许 GET 请求访问资源。您可以包含其他 HTTP 方法,例如 POST、PUT、DELETE 等,以限制允许访问资源的方法。

  • "maxAgeSeconds": 3600 在浏览器中缓存 CORS 配置 1 小时(3600 秒)。在缓存期间,来自同一来源和方法的后续请求将不需要进行 CORS 检查。

创建 cors.json 文件后,以及安装 gsutil,在终端中执行此命令:

gsutil cors set cors.json gs://<bucket>.appspot.com

确保将 替换为您的存储桶的名称。

通过执行这些步骤,我能够解决 CORS 问题并启用对我的资源的访问。

I resolved this problem by adjusting the CORS settings on the server side. Initially, I thought it was a client problem, but it turned out to be caused by a misconfiguration on the server.

In my case, I was using Firebase Storage, and I had to create a cors.json file on my computer to enable CORS. Here's what my configuration looked like:

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

To break this down:

  • "origin": ["*"] allows requests from any origin to access the resource. You can specify a specific domain or a list of domains to restrict the origins that are allowed to access the resource.

  • "method": ["GET"] allows only GET requests to access the resource. You can include other HTTP methods like POST, PUT, DELETE, etc. to restrict the methods that are allowed to access the resource.

  • "maxAgeSeconds": 3600 caches the CORS configuration in the browser for 1 hour (3600 seconds). Subsequent requests from the same origin and method will not require a CORS check during the cache duration.

After creating the cors.json file, and after installing gsutil, execute this command in your terminal:

gsutil cors set cors.json gs://<bucket>.appspot.com

Make sure to replace <bucket> with the name of your storage bucket.

By following these steps, I was able to fix my CORS issue and enable access to my resources.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文