我正试图从我(用python(制作的API中获取数据到我的Flutter网站,但我要求API响应的代码块没有运行。我尝试了我所知道的一切,但给出的错误很奇怪。
这是我在中出错的代码
import 'package:http/http.dart' ;
import 'dart:convert';
const String url = 'http://localhost:5000/api?imagenumber=' ;
Future getImageIds(int image) async {
Response response = await get( url + image.toString()) ;
dynamic responsBody = response.body ;
dynamic decodedData = jsonDecode(responsBody) ;
return decodedData ;
}
顺便说一下,API正在本地主机上运行(目前(。
这里是错误:
Performing hot restart...
Syncing files to device Chrome...
Restarted application in 605ms.
This if from screen 1: 1 , 2 , 3
Error: XMLHttpRequest error.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 906:28 get current
packages/http/src/browser_client.dart 84:22 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1450:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 143:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 696:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 725:32 _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 519:7 [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1302:7 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37312:58 <fn>
at Object.createErrorWithStack (http://localhost:55081/dart_sdk.js:4361:12)
at Object._rethrow (http://localhost:55081/dart_sdk.js:38188:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:55081/dart_sdk.js:38182:13)
at Object._microtaskLoop (http://localhost:55081/dart_sdk.js:38014:13)
at _startMicrotaskLoop (http://localhost:55081/dart_sdk.js:38020:13)
at http://localhost:55081/dart_sdk.js:33517:9
忽略前四行
您需要启用跨来源资源共享(CORS(才能发出请求。如果启用了CORS,您将不会再出现此错误。我也遇到了同样的问题,决定通过云功能提出请求。你可以考虑启用cors,可能有一种方法可以让它在谷歌chrome中进行测试。
添加:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
到您的服务器.htaccess