4

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.

and

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

Here is the code i use to make HTTP requests using '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);
    });
  }

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain what this issue is, and is it a flutter specific issue? We're calling an API using python and flutter ate different devices and the one with python is working fine but the flutter is giving this error XMLHttpRequest error
No usually, it's not a flutter specific issue it happened to me even in NodeJS, I am not extremely experienced in these type of issues, I suggest you to make a question and see what people tell you, thanks for reaching out anyways!
0

If you're using PHP. Add below code to your .htaccess file (located in root folder)

<ifModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www.)?(localhost:CHANGE_THIS_WITH_PORT_NUMBER|somedomain.com)$" AccessControlAllowOrigin=$0
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header always set Access-Control-Allow-Methods: "GET,POST,PUT,DELETE,OPTIONS"
</ifModule> 

Comments