In Flutter Web Getting 'Xmlhttprequest' Error While Making Http Call

XMLHttpRequest error in flutter web [Enabling CORS AWS API gateway]

this worked for me, I added the below header on the lambda function

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)
};

XMLHttpRequest error while using http post flutter web

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"] = "fake@gmail.com";
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());
});
}


Related Topics



Leave a reply



Submit