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

如何解决Flutter中使用http库请求URL时出现的XMLHttpRequest错误

Fixing XMLHttpRequest Error in Flutter When Fetching from Firebase Storage

Hey Diego, let's work through this XMLHttpRequest error you're facing when trying to fetch your sensores.json file from Firebase Storage. Here are the most common fixes to try:

1. Remove Unnecessary Request Headers

First, notice you're sending Access-Control-Allow-Origin and Access-Control-Allow-Headers in your request—these are response headers, not request headers. The client (your Flutter app) doesn't send these; they're sent by the server to tell the browser it's allowed to access the resource. Including them in your request can actually cause issues with the CORS check.

Update your code to only include the Accept header:

Future<List<Sensor>> fetchSensores() async {
  final response = await http.get(
    Uri.parse(
      'https://firebasestorage.googleapis.com/v0/b/ecosolutions-73ab2.appspot.com/o/sensores.json?alt=media&token=09ac9e63-744d-4286-aae1-c4eadd81c026'
    ),
    headers: {
      "Accept": "application/json",
    }
  );

  if (response.statusCode == 200) {
    return compute(parseSensores, response.body);
  } else {
    throw Exception('Failed to load sensors');
  }
}

2. Configure CORS for Firebase Storage

The main culprit here is almost certainly missing CORS configuration on your Firebase Storage bucket. By default, Firebase Storage restricts cross-origin requests, so you need to explicitly allow your app's domain (or all domains for development) to access the files.

Step 1: Create a cors.json file

Create a file named cors.json with the following content (this allows GET requests from any origin for development; replace ["*"] with your production domain later):

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

Step 2: Apply the CORS configuration

Make sure you have the Google Cloud SDK installed (which includes the gsutil tool), then run this command to set the CORS policy on your bucket:

gsutil cors set cors.json gs://ecosolutions-73ab2.appspot.com

3. Verify File Accessibility

Double-check that the sensores.json file in Firebase Storage is accessible with the token you're using. Try opening the full URL directly in your browser—if it loads the JSON correctly, the token is valid; if not, you may need to regenerate the download token or adjust the file's privacy settings.

Once you've made these changes, restart your Flutter app and test the fetch again—this should resolve the XMLHttpRequest error.

内容的提问来源于stack exchange,提问作者Diego jiménez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:22:37