【问题标题】:Error during http request in Firebase function generated by dart2js: ReferenceError: XMLHttpRequest is not defineddart2js 生成的 Firebase 函数中的 http 请求期间出错:ReferenceError: XMLHttpRequest is not defined
【发布时间】:2026-01-25 20:25:01
【问题描述】:

我正在使用 dart2js 创建 firebase 函数。在这样的函数中,我必须为某些 Web api 调用 http 请求(在此示例中,是对 www.google.com 的简单网站请求 :-)),但得到“ReferenceError: XMLHttpRequest is not defined”。在 Android 或 iOS 上的 Dart 应用程序中运行相同的代码可以正常工作。我正在使用https://pub.dev/packages/http

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

class ExecuteHttpRequest {
  Future<void> execute() async {
    Uri getUri = Uri.https('www.google.com', '');
    final response = await http.get(getUri);
    if (response.statusCode == 200) print('success');
  }
}

类是例如包裹在一个简单的 firebase 函数中

import 'package:node_io/node_io.dart';
import 'package:firebase_functions_interop/firebase_functions_interop.dart';
import 'package:nodejs_test/ExecuteHttpRequest.dart';

void main() {
  functions['executeHttpRequest'] = functions.https.onRequest((ExpressHttpRequest request) async {
    await ExecuteHttpRequest().execute();
    request.response
      ..headers.contentType = ContentType.text
      ..write("success :-)")
      ..close();
  });
}

在构建和执行时,我得到以下信息:

 % pub run build_runner build -o node:build
[INFO] Generating build script completed, took 301ms
[WARNING] The package `nodejs_test` does not include some required sources in any of its targets (see their build.yaml file).
The missing sources are:
  - $package$
[INFO] Reading cached asset graph completed, took 178ms
[INFO] Checking for updates since last build completed, took 611ms
[INFO] Running build completed, took 184ms
[INFO] Caching finalized dependency graph completed, took 117ms
[INFO] Reading manifest at build/.build.manifest completed, took 0ms
[INFO] Deleting previous outputs in `build` completed, took 144ms
[INFO] Creating merged output dir `build` completed, took 614ms
[INFO] Writing asset manifest completed, took 3ms
[INFO] Succeeded after 1.1s with 0 outputs (0 actions)

 % firebase emulators:start                
i  emulators: Starting emulators: functions, firestore, database, hosting
⚠  functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: auth, pubsub
⚠  Your requested "node" version "10" doesn't match your global version "14"
i  firestore: Firestore Emulator logging to firestore-debug.log
i  database: Database Emulator logging to database-debug.log
⚠  hosting: Authentication error when trying to fetch your current web app configuration, have you run firebase login?
⚠  hosting: Could not fetch web app configuration and there is no cached configuration on this machine. Check your internet connection and make sure you are authenticated. To continue, you must call firebase.initializeApp({...}) in your code before using Firebase.
i  hosting[nodejs-test]: Serving hosting files from: public
✔  hosting[nodejs-test]: Local server: http://localhost:5000
i  ui: Emulator UI logging to ui-debug.log
i  functions: Watching "/Users/stefano/development/nodejs-test/functions" for Cloud Functions...
✔  functions[executeHttpRequest]: http function initialized (http://localhost:5001/nodejs-test/us-central1/executeHttpRequest).

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4000                │
└─────────────────────────────────────────────────────────────┘

┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator  │ Host:Port      │ View in Emulator UI             │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4000/functions │
├───────────┼────────────────┼─────────────────────────────────┤
│ Firestore │ localhost:8080 │ http://localhost:4000/firestore │
├───────────┼────────────────┼─────────────────────────────────┤
│ Database  │ localhost:9000 │ http://localhost:4000/database  │
├───────────┼────────────────┼─────────────────────────────────┤
│ Hosting   │ localhost:5000 │ n/a                             │
└───────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500

Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.
 
i  functions: Beginning execution of "executeHttpRequest"
>  /Users/stefano/development/nodejs-test/functions/build/index.dart.js:8378
>        throw error;
>        ^
>  
>  ReferenceError: XMLHttpRequest is not defined
>      at /Users/stefano/development/nodejs-test/functions/build/index.dart.js:10055:15
>      at _wrapJsFunctionForAsync_closure.$protected (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3431:15)
>      at _wrapJsFunctionForAsync_closure.call$2 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7301:12)
>      at _awaitOnObject_closure.call$1 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7287:32)
>      at _RootZone.runUnary$2$2 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:8450:18)
>      at _Future__propagateToListeners_handleValueCallback.call$0 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7689:61)
>      at Object._Future__propagateToListeners (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3530:104)
>      at _Future._completeWithValue$1 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7502:9)
>      at _Future__asyncComplete_closure.call$0 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7604:10)
>      at Object._microtaskLoop (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3593:21) {
>    dartException: <ref *1> ReferenceError: XMLHttpRequest is not defined
>        at /Users/stefano/development/nodejs-test/functions/build/index.dart.js:10055:15
>        at _wrapJsFunctionForAsync_closure.$protected (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3431:15)
>        at _wrapJsFunctionForAsync_closure.call$2 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7301:12)
>        at _awaitOnObject_closure.call$1 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7287:32)
>        at _RootZone.runUnary$2$2 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:8450:18)
>        at _Future__propagateToListeners_handleValueCallback.call$0 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7689:61)
>        at Object._Future__propagateToListeners (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3530:104)
>        at _Future._completeWithValue$1 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7502:9)
>        at _Future__asyncComplete_closure.call$0 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7604:10)
>        at Object._microtaskLoop (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3593:21) {
>      '$cachedTrace': _StackTrace {
>        _exception: [Circular *1],
>        _trace: 'ReferenceError: XMLHttpRequest is not defined\n' +
>          '    at /Users/stefano/development/nodejs-test/functions/build/index.dart.js:10055:15\n' +
>          '    at _wrapJsFunctionForAsync_closure.$protected (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3431:15)\n' +
>          '    at _wrapJsFunctionForAsync_closure.call$2 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7301:12)\n' +
>          '    at _awaitOnObject_closure.call$1 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7287:32)\n' +
>          '    at _RootZone.runUnary$2$2 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:8450:18)\n' +
>          '    at _Future__propagateToListeners_handleValueCallback.call$0 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7689:61)\n' +
>          '    at Object._Future__propagateToListeners (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3530:104)\n' +
>          '    at _Future._completeWithValue$1 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7502:9)\n' +
>          '    at _Future__asyncComplete_closure.call$0 (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:7604:10)\n' +
>          '    at Object._microtaskLoop (/Users/stefano/development/nodejs-test/functions/build/index.dart.js:3593:21)'
>      }
>    }
>  }

【问题讨论】:

  • 你能写一篇关于这个的教程吗 - 学习如何创建和部署用 Dart 编写的函数到 Google/Firebase Cloud Functions 会很棒!我一直在努力研究这个!

标签: node.js dart google-cloud-functions dart2js dart-http


【解决方案1】:

现在我自己解决了这个问题:-)

你必须使用

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

而不是

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

【讨论】: