我对 Dart 相当陌生,并且很难解决此错误,该错误出现在此处的相当多的问题中:
Error: XMLHttpRequest error.
我的现实场景是一个 Flutter Web 应用程序,它应该能够访问 Google Cloud Function,但本着 MWE 的精神,我用这个 Dart 复制了这个问题:
import 'dart:developer';
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> main() async {
final response = await http.post(
Uri.https(
//'jsonplaceholder.typicode.com', 'albums'),
'my-region-my-project.cloudfunctions.net',
'/remainingTrigger'),
headers: <String, String>{
//'Content-Type': 'application/json; '
// 'charset=UTF-8',
'Content-Type': 'application/json'
},
body: jsonEncode(<String, String>{
//'title': 'test',
'ingredients': 'test',
}),
);
log('response was ${response.body}');
}
headers
注释似乎没有什么区别,但如果我翻转其他注释,它与 JSONPlaceholder 一起工作得很好。如果我在终端中使用 curl
点击我的云功能
$ curl -X POST -H "Content-Type: application/json" -d '{"ingredients": "test"}' https://my-region-my-project.cloudfunctions.net/remainingTrigger
{"key":"value","otherKey":"otherValue"}
效果很好。我最初确实遇到了 CORS 问题(我的云功能日志显示 417),但在我添加之后
from flask import abort
def entryPoint(request):
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
...
headers = {
'Access-Control-Allow-Origin': '*'
}
...
return (expectedOutput, 200)
...
else:
return abort(417)
Cloud Function 日志开始显示正常行为(首先是 204,然后是 200)。如果云功能说一切正常,而 Dart 不同意,是否可以排除 CORS 是罪魁祸首?我只处理过 CORS 一次,但我对云功能的设置非常相似,并且 Web 开发人员能够与它进行良好的交互。
回溯对我来说是希腊语;有人可以提供建议来辨别导致错误的
XMLHttpRequest
问题类型吗?
我主要在 Windows 10 Home(
http: ^0.13.1
、Dart SDK 2.12.2、Flutter 2.0.4、Android SDK 29.0.2)上运行的 Android Studio 4.1.3(Chrome 模拟器)中对此进行故障排除,但也构建和部署它曾经访问过我的网站,遇到了同样的错误(Safari)。我正在从 Big Sur 11.0.1 上的 Docker 容器部署 Cloud Function(Python 3.8 运行时),但我认为这没有什么区别。
令我惊讶的是,当我在 Android Studio 的 Android 模拟器(Pixel 3、API 30、Android 11.0)中尝试我的代码时,效果很好。只是 Flutter Web 尝试失败了(我现在已经通过 Android Studio 尝试使用 Chrome 和 Edge,并在生产环境中尝试使用 Safari)。其他人看到这种行为吗?
我也在供应商的 API 中看到了这种行为,因此它不是特定于我的 Google Cloud Function 的。 Flutter Web 版和 JSONPlaceholder API 的组合有什么特别之处吗?
我遇到了同样的问题,它似乎与跨域相关。可以通过云函数中的响应发送 {'Access-Control-Allow-Origin': '*'} 来修复。响应应如下所示:
return ('Any response body', 200, {'Access-Control-Allow-Origin': '*'})
这感觉仍然像是 CORS 问题。 Firebase 最近发布了gen 2 Cloud Functions,提供了更简单的添加 CORS 的方法。
允许所有来源:
const { onRequest } = require("firebase-functions/v2/https");
exports.sayHello = onRequest(
{ cors: true },
(req, res) => {
res.status(200).send("Hello world!");
}
);
允许您的来源:
const { onRequest } = require("firebase-functions/v2/https");
exports.sayHello = onRequest(
{ cors: ["my-site.com"] },
(req, res) => {
res.status(200).send("Hello world!");
}
);