Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you remove the "XMLHttpRequest error" in Flutter? (Django backend, Flutter frontend)

I'm having trouble connecting my Django backend to my Flutter frontend on web.I have not tested on Android or iOS yet.

I want to be able to do an API call and have it return a response that I can convert to a json. However it's been throwing errors no matter what I've tried. I've tried converting it into an https request with no avail.

If anyone needs anything on the Django side please let me know

This is what the error looks like:

Error: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 909:28                get current

packages/http/src/browser_client.dart 71:22                                       <fn>

dart-sdk/lib/async/zone.dart 1613:54 runUnary dart-sdk/lib/async/future_impl.dart 155:18 handleValue dart-sdk/lib/async/future_impl.dart 707:44 handleValueCallback dart-sdk/lib/async/future_impl.dart 736:13 _propagateToListeners dart-sdk/lib/async/future_impl.dart 533:7 [_complete] dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue dart-sdk/lib/async/stream.dart 1219:7 dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall dart-sdk/lib/html/dart2js/html_dart2js.dart 37307:58

at Object.createErrorWithStack (http://localhost:63593/dart_sdk.js:5362:12)
at Object._rethrow (http://localhost:63593/dart_sdk.js:39509:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:63593/dart_sdk.js:39503:13)
at Object._microtaskLoop (http://localhost:63593/dart_sdk.js:39335:13)
at _startMicrotaskLoop (http://localhost:63593/dart_sdk.js:39341:13)
at http://localhost:63593/dart_sdk.js:34848:9

And this is a code snippet

import 'package:http/http.dart' as http;

var url2 = 'https://0.0.0.0:8809/test/';
              try{
                response = await http.get(Uri.parse(url2));
                print(response.body);
              }
              catch(exception){
                print('could not access');
                    response = await http.get(Uri.parse(url2));
              }

            },

I had it print out the error.

like image 903
gdxgrace Avatar asked Feb 27 '26 12:02

gdxgrace


1 Answers

It might be caused because CORS is not enabled in your backend. It happens because your server and frontend are present on different IPs (Even if you are doing your work on localhost, the port is still different).

To solve this you you just have to add parameters to enable CORS in your response header. There are packages available for that acts as a middleware so you wont have to add it in every response. Refer the below question :

How can I enable CORS on Django REST Framework

like image 85
Sarvesh Dalvi Avatar answered Mar 01 '26 10:03

Sarvesh Dalvi