IN Flutter Web getting 'XMLHttpRequest' error while making HTTP call
Asked Answered
K

10

31

I am using XAMPP control panel and using a local server like Apache port no 80, but in flutter web getting XMLHttpRequest error and in mobile device. The same coding fetches data using API not getting any error. How to fetch data using API while app run on flutter-web?

Error

Launching lib\main.dart on Chrome in debug mode...
Syncing files to device Chrome...
Debug service listening on ws://127.0.0.1:56619/FsXy3a4ZrZg=
Debug service listening on ws://127.0.0.1:56619/FsXy3a4ZrZg=
Error: XMLHttpRequest error.
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 906:28                get current
packages/http/src/browser_client.dart 84:22                                                                                    <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1450:54                                              runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 143:18                                        handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 696:44                                        handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 725:32                                        _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 519:7                                         [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11                                         _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1302:7                                             <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14  _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39  dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37312:58                              <fn>
    
    at Object.createErrorWithStack (http://localhost:5555/dart_sdk.js:4361:12)
    at Object._rethrow (http://localhost:5555/dart_sdk.js:38189:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:5555/dart_sdk.js:38183:13)
    at Object._microtaskLoop (http://localhost:5555/dart_sdk.js:38015:13)
    at _startMicrotaskLoop (http://localhost:5555/dart_sdk.js:38021:13)
    at http://localhost:5555/dart_sdk.js:33518:9

Backend Side PHP Webservice

<?php

header("Access-Control_Allow_Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Content-type:application/json;charset=utf-8"); 
header("Access-Control-Allow-Methods: GET");

include 'config.php';

$sql="select * from calinsert";
$result=mysqli_query($conn,$sql)or die("query failed");

if(mysqli_num_rows($result) >0){
    $output=mysqli_fetch_all($result,MYSQLI_ASSOC);
    echo json_encode($output);
}
else{   
    echo json_encode(array('message'=>'no record found','status'=>false));
}
?>

Flutter Side Code

Future getdata()async {
    final response = await http.get(
        'http://localhost:80/web_service/calview.php',
        headers: {
          "Accept": "application/json",
          "Access-Control_Allow_Origin": "*"
        });

    print(response.statusCode);
    print(response.body);
  }
Kedge answered 21/10, 2020 at 7:31 Comment(1)
I have the same Problem do you have a solution?Billibilliard
D
12

In most cases of Flutter API use, add Access-Control-Allow-Origin value in header might resolve the issue. (Note: This will help in access the local or external APIs)

header("Access-Control-Allow-Origin: *");

Hint: you have typo in your above header, please check and correct.

Dyslexia answered 26/10, 2020 at 12:46 Comment(3)
This is most likely the problem as many others with this error solved it by adding CORS to their request header. I didn't catch the type as you did.Oahu
Where in my file do I have to to put the code?Arietta
@Arietta its header part, where you define Content-typeDyslexia
H
4

Just removed the header attribute from the post method and it works for me.

Hammerlock answered 27/6, 2021 at 9:36 Comment(1)
Yes, But I need to send headers with my post request!!!!Albania
R
3
  1. Fix the typo (replace underscores by dashes):

     header("Access-Control-Allow-Origin: *");
    
  2. Add the following header in your php code:

    header("Access-Control-Allow-Headers": "Access-Control-Allow-Origin, Accept");
    
Rugen answered 10/5, 2021 at 23:27 Comment(1)
2 nd point not understood can you share some examples? i m use laravel for api.Goldiegoldilocks
O
1

I was recently getting this error as well and I seem to have fixed by upgrading my package to the most recent 0.12.2 version and it seems to have helped - so far.

https://pub.dev/packages/http

Oahu answered 23/10, 2020 at 2:31 Comment(4)
@DarpitPatel - have you checked the browser console to see if there is any more specific errors that might help identify the root cause? github.com/dart-lang/http/issues/433Oahu
Is this issue only for web app or also getting issue for mobile app deployment?Dyslexia
@JubinPatel yes it's only on flutter web appComplexioned
did you find the solution?Unriddle
L
1

Simply it is CORS error. you have to add "localhost:XXXX" or the corresponding address to the CORS origins in the backend code to get it run in debug mode. Eg: in FastAPI, CORS Management in FastAPI

Lento answered 2/10, 2022 at 0:34 Comment(0)
M
1

I got the same error message and tried all to config the CORS policies right and it was working from the browser with a simple Javascript fetch but not with Flutter Web http.

Long story short, it fails becausee of my self signed certificate.

As it turned out the badCertificateCallback i was using for Flutter mobile is not working with Flutter web.

Maybe that helps someone.

Marthamarthe answered 14/7, 2023 at 12:51 Comment(0)
F
0

Thank you! F12 Tools -> Access to XMLHttpRequest at 'https://localhost:44360/xxyy' from origin 'http://localhost:52273' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

More info - CORS is usually a sever side issue, you have to set up what clients are allowed. For development purposes, my flutter web is talking to a .net core service so I had to enable CORS in development mode only to allow CORS using the following:

builder
                .AllowAnyOrigin()
                .WithHeaders(HeaderNames.AccessControlAllowHeaders, "Content-Type")
                .AllowAnyMethod();

        }));
French answered 18/3, 2021 at 4:15 Comment(2)
what is the solution ?Livelong
I updated post with my service config using .net core. Your service might be different. Basically allow CORS for development.French
S
0

The problem arose for me with my Appwrite server. I just had to add localhost as a trusted web app and it started working without issues.

Stulin answered 2/12, 2021 at 10:1 Comment(1)
Can you explain how you did that?Albania
G
0

enter image description here

While I deployed flutter application apache xampp server i receive below error.

FrontEnd in Flutter (abc.com) Backend in laravel (apiabc.com)

there a 2 domain

Goldiegoldilocks answered 21/9, 2023 at 14:6 Comment(0)
A
0

you have to add "https://app.flutterflow.io" to your list of allowed origins from your app

Apteral answered 28/9, 2023 at 11:58 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Conciliator

© 2022 - 2024 — McMap. All rights reserved.