Atul Chaudhary
Atul Chaudhary

Reputation: 1779

XMLHttpRequest error while using http post flutter web

I am facing this error XMLHttpRequest error. while making an HTTP post call to my API-AWS API Gateway. My current Flow is Flutter web -> API gateway -> lambda -> rds.

I know there are already a couple of question-related to this like but as suggested in one of the answers to add some headers in response to lambda. but it doesn't work for me.

After doing some research I found out that the problem is regarding to CORS. now disabling cors in chrome is a temporary fix and suggested in this question.

some other solution that I found after researching suggested to enabled cors in my API and also in the frontend part I have added headers but none of them works.

fetchData() async {
    String url =
        "myUrl";
    Map<String, String> headers = {
      "Access-Control-Allow-Origin": "*", // Required for CORS support to work
    };
    String json = '{"emailId":"emailId"}';
    http.Response response =
        await http.post(Uri.parse(url), headers: headers, body: json);
    print(response.body);
    return response.body;
  }

what is the correct way of solving this problem?

Upvotes: 3

Views: 26172

Answers (7)

Madhav Asok
Madhav Asok

Reputation: 1

I was facing the same issue with Azure Storage service. I had to enable CORS on the storage account settings in addition to adding the header: 'Access-Control-Allow-Origin: *' in the post request.

Upvotes: 0

Imen A.
Imen A.

Reputation: 837

it works on the web app developed with flutter ! ^^ if you uses php in your backend, add these lines as below

   <? php  
header('Access-Control-Allow-Origin: *');   
header("Access-Control-Allow-Credentials: true");  
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); 
header('Access-Control-Max-Age: 1000');  
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

Upvotes: 1

ALNAJJAR
ALNAJJAR

Reputation: 483

1- Go to flutter\bin\cache and remove a file named: flutter_tools.stamp

2- Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.

3- Find '--disable-extensions'

4- Add '--disable-web-security'

Upvotes: 11

Amir Hosseinzadeh
Amir Hosseinzadeh

Reputation: 8458

To check HTTP and HTTPS and Port 80

I encountered an issue with my Flutter project, which was functioning properly on my Android device, but not on Google Chrome. The error message indicated a problem with XMLHttpRequest. After conducting some troubleshooting, I discovered that the root of the issue was related to the use of unencrypted HTTP connections. By checking the URLs for HTTP and HTTPS, I was able to identify the problem and take appropriate action to rectify it.

Upvotes: 1

yaser sojoodi
yaser sojoodi

Reputation: 31

in your backend php file add this code

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

finish!

Upvotes: 0

Jay Nirmal
Jay Nirmal

Reputation: 400

In flutter web api Access-Control-Allow-Origin use in header to might resolve this issue.

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

Upvotes: 0

Atul Chaudhary
Atul Chaudhary

Reputation: 1779

I have Solved my problem, and not going to delete this question because there aren't many well-defined solutions to this problem. For Future viewer who is using flutter web and AWS API-gateway.

  1. if you encounter this problem it means its from backend side not from flutter side
  2. XMLHttpRequest error. is caused due to CORS

The solution to the problem you have to enable CORS in api-gateway follow this link.

but if you are using proxy integration with lambda and api-gateway then in that case enabling CORS doesn't going to help, you have to pass on headers from the response of lambda function. like

return {
    statusCode: 200,
     headers: {
  "Access-Control-Allow-Origin": "*", // Required for CORS support to work
  "Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
  "Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
  "Access-Control-Allow-Methods": "POST, OPTIONS"
},
    body: JSON.stringify(item)
};

the format needs to be the same. also, one particular question that helps me a lot to understand this whole issue is going through the various answer of the question link.

Now comes my problem, what I'm doing wrong i that i am passing "Access-Control-Allow-Origin": "*", from frontend and enabling CORS in API gateway also send similar headers which are creating a problem for me

Access to XMLHttpRequest at 'API-URL' from origin 'http://localhost:63773' 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.  //this particular line

So after changing my function to this everything works perfectly fine

fetchData() async {
    String url =
        "API-url";
    Map<String, String> headers = {
      "Content-Type": "text/plain",
    };
    String json = '{"emailId":"emailId"}';
    Map<String, String> map = Map();
    map["emailId"] = "[email protected]";
    http.Response response = await http
        .post(Uri.parse(url), headers: headers, body: jsonEncode(map))
        .then((value) {
      print("onThen> " + value.body.toString());
    }).onError((error, stackTrace) {
      print("onError> " +
          error.toString() +
          " stackTrace> " +
          stackTrace.toString());
    });
  }

Upvotes: 8

Related Questions