如何在Flutter for Web上发出HTTP请求? [英] How to make HTTP Requests on Flutter For Web?

查看:812
本文介绍了如何在Flutter for Web上发出HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个执行对NodeJS服务器的HTTP请求的应用程序,但是当我执行HTTP请求时,结果如下:

I am building an application that executes HTTP requests to a NodeJS Server but when i execute an HTTP request the result is the following:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Uncaught (in promise) Error: XMLHttpRequest error.
    dart:sdk_internal 41864:30                                    get current
package:http/src/packages/http/src/browser_client.dart 84:22  <fn>
dart:sdk_internal 99587:96                                    <fn>


    at Object.dart.createErrorWithStack (dart_sdk.js:4617)
    at Object.async._rethrow (dart_sdk.js:28723)
    at async._AsyncCallbackEntry.new.callback (dart_sdk.js:28719)
    at Object.async._microtaskLoop (dart_sdk.js:25352)
    at async._startMicrotaskLoop (dart_sdk.js:25358)
    at dart_sdk.js:25433

这是我使用发出HTTP请求的代码package:http / http.dart'as http;

void requestGet(String endpoint, Callback cb) async {
    return await http.get(Uri.encodeFull(url + endpoint),
        headers: {"Accept": "application/json"}).then((http.Response response) {
      print(response.body);
    });
  }

  void requestPost(String endpoint, Map data, Callback cb) async {
    return await http.post(Uri.encodeFull(url + endpoint),
        body: data,
        headers: {"Accept": "application/json"}).then((http.Response response) {
      print(response.body);
    });
  }


推荐答案

保护HTTP请求的问题通过在我的NodeJS服务器中启用CORS即可解决。此处是文档。

The problems reguarding the HTTP requests were solved by enabling CORS in my NodeJS Server here is the documentation.

这篇关于如何在Flutter for Web上发出HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆