Flutter DioError [DioErrorType.response]: XMLHttpRequest error

Viewed 2206

I have a Localhoset and want to get the data from this local host in Flutter and show it with clicking on the button. the get request successfully finishes but the nstead of printing the result i recieve the following error!

> Running with unsound null safety
For more information see https://dart.dev/null-safety/unsound-null-safety
Debug service listening on ws://127.0.0.1:59432/vuDMHfesIRs=/ws
DioError [DioErrorType.response]: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 909:28   get current
packages/dio/src/dio_mixin.dart 819:20                               assureDioError
packages/dio/src/dio_mixin.dart 678:13                               _dispatchRequest
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 60:31   <fn>
dart-sdk/lib/async/zone.dart 1618:54                                 runBinary
dart-sdk/lib/async/future_impl.dart 169:20                           handleError
dart-sdk/lib/async/future_impl.dart 719:46                           handleError
dart-sdk/lib/async/future_impl.dart 740:13                           _propagateToListeners
dart-sdk/lib/async/future_impl.dart 550:5                            [_completeError]
dart-sdk/lib/async/future_impl.dart 606:7                            callback
dart-sdk/lib/async/schedule_microtask.dart 40:11                     _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5                      _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15  <fn>

I test the same code and the same Process with anothe api it was working! what could it be?

here is the get method:

    Dio dio = new Dio();
  void getCountries() async{
    try {
      var response = await dio.get('http://b21dfa1ea157.ngrok.io/gettest'
      );

      dio.options.headers['content-Type'] = 'text/plain; charset=UTF-8';
      dio.options.headers['Access-Control-Allow-Origin'] = '*';
      dio.options.headers['Access-Control-Allow-Methods'] = 'GET , POST';

      print(response.data);
    } catch (e) {
      print(e);
    }
  }

and also through clicking the Button it calls the method:

RaisedButton(onPressed: getMethod)

Could anybody help me?

1 Answers

This seems to be a CORS (cross-origin resource sharing) issue. Common workarounds made here for development builds is by disabling security using --disable-web-security argument when the app is run.

For production builds, you need to enable the CORS request on your server-side to fix this. Depending on your setup, you won't be needing to make changes on the client app.

Related