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

使用dart2js开发Firebase Functions遇XMLHttpRequest未定义错误

解决Firebase Functions中Dart http包的"ReferenceError: XMLHttpRequest is not defined"错误

这个问题的核心原因很明确:你使用的http包默认采用浏览器环境的XMLHttpRequest API发起请求,但Firebase Functions运行在Node.js环境中,Node.js并没有内置XMLHttpRequest对象,所以才会抛出这个未定义错误。

解决方案:切换到Node.js兼容的HTTP客户端

你可以通过两种方式解决这个问题:

方式1:直接使用node_io包的HttpClient

node_io是Dart对Node.js IO API的封装,它的HttpClient原生适配Node环境,不需要依赖浏览器API。

修改你的ExecuteHttpRequest类:

import 'package:node_io/node_io.dart';

class ExecuteHttpRequest {
  Future<void> execute() async {
    final client = HttpClient();
    try {
      // 创建请求
      final request = await client.getUrl(Uri.https('www.google.com', ''));
      // 发送请求并获取响应
      final response = await request.close();
      
      if (response.statusCode == 200) {
        print('success');
      }
    } finally {
      // 务必关闭客户端释放资源
      client.close();
    }
  }
}

方式2:为http包配置Node兼容的客户端

如果你想继续使用http包的API风格,可以用http.IOClient包装node_io的HttpClient,这样就能在Node环境中复用原有的http包调用方式:

import 'package:http/http.dart' as http;
import 'package:node_io/node_io.dart';

class ExecuteHttpRequest {
  Future<void> execute() async {
    // 用Node的HttpClient创建兼容的IOClient
    final client = http.IOClient(NodeHttpClient());
    try {
      Uri getUri = Uri.https('www.google.com', '');
      final response = await client.get(getUri);
      
      if (response.statusCode == 200) {
        print('success');
      }
    } finally {
      client.close();
    }
  }
}

为什么原来的代码在移动端正常?

Android/iOS的Dart应用运行在Flutter引擎中,Flutter为http包提供了适配移动端的底层实现(并非依赖浏览器的XHR),所以在移动端可以正常工作,但Node.js环境没有这个适配层,必须手动切换到Node兼容的客户端。

内容的提问来源于stack exchange,提问作者Dr. Stefano Merenda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:26:21