[SOLVED] XMLHttpRequest error in Flutter web is a CORS error

This is the error from http package in Flutter:

Error: XMLHttpRequest error.
    dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 908:28                get current
packages/http/src/browser_client.dart 69:22                                       <fn>
dart-sdk/lib/async/zone.dart 1687:54                                              runUnary
dart-sdk/lib/async/future_impl.dart 160:18                                        handleValue
dart-sdk/lib/async/future_impl.dart 767:44                                        handleValueCallback
dart-sdk/lib/async/future_impl.dart 796:13                                        _propagateToListeners
dart-sdk/lib/async/future_impl.dart 593:7                                         [_complete]
dart-sdk/lib/async/stream_pipe.dart 61:11                                         _cancelAndValue
dart-sdk/lib/async/stream.dart 1232:7                                             <fn>
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14  _checkAndCall
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39  dcall
dart-sdk/lib/html/dart2js/html_dart2js.dart 37332:58                              <fn>

    at Object.createErrorWithStack (http://localhost:46627/dart_sdk.js:5074:12)
    at Object._rethrow (http://localhost:46627/dart_sdk.js:38925:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:46627/dart_sdk.js:38921:13)
    at Object._microtaskLoop (http://localhost:46627/dart_sdk.js:38778:13)
    at _startMicrotaskLoop (http://localhost:46627/dart_sdk.js:38784:13)
    at http://localhost:46627/dart_sdk.js:34519:9

This error is a Javascript error and it can be inspected from AndroidStudio terminal or from the browser console.

If you run into this problem it means that the requests to the API server are failing due to a CORS error.

When executing these types of requests from the web page, a sort of “pre authorization request” is made to the server. This request is an OPTIONS request that must be answered with a 2xx response. This is called PreFlight authorization. Make sure that your application is accepting the OPTIONS method.

A second step is the request itself (for example with GET method).

To allow a correct answer from the server, you need to add some headers to the response. In case you are using Apache, you have to set the following headers:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Headers "Content-Type"
    Header set Referrer-Policy "no-referrer-when-downgrade"


Buy Me A Coffee

This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.