Home > Blockchain >  Getting XMLHttpRequest error from POST request in flutter
Getting XMLHttpRequest error from POST request in flutter

Time:06-02

I am trying to make a post request to an API in flutter and it works perfectly when I use cURL on the command line but the request in flutter doesn't work. Tried a ton of different request formats but nothing works.

Here is the working cURL request: (the API correctly returns a string with details about the YouTube video)

curl -m 70 -X POST <API_URL_HERE> \
-H "Content-Type:application/json" \
-d '{"youtube_link":"https://www.youtube.com/watch?v=gbUfbN7vT20"}'

Here is the not working Flutter request:

String link = "https://www.youtube.com/watch?v=gbUfbN7vT20";
var url = Uri.parse("<API_URL_HERE>");
var response = await http.post(url, 
                  body: jsonEncode({"youtube_link": "$link"}), 
                  headers: {"Content-Type": "application/json"}
               );

Error: XMLHttpRequest error. I checked on the server that is receiving the request. With the good request it returns a status code of 200 and on the Flutter request it returns a status code of 400 (but no errors are occurring in the actual code, it seems to be just a problem with the request).

Update: Ok, it seems it was a CORS issue. However I haven't managed to fix it on the API side either by following these instructions https://cloud.google.com/functions/docs/writing/http#handling_cors_requests

although that is probably a separate question.

CodePudding user response:

You can user POST method in this way... Example of user register in my app

void register(User user) async {

var url = Uri.parse(base_url   '/register');

final http.Response response = await http.post(
  url,
  headers: <String, String>{
    'Content-Type': 'application/json',
    'Accept-Language': 'en-US',
  },
  body: json.encode(user.toJson()),
);

if (kDebugMode) {
  print(response.body.toString());
}
var answer = jsonDecode(response.body);
String returnAnswer = "";
if (response.statusCode == 200) {
  try {
    ////code for success...
  } catch (_) {
    return returnAnswer;
  }
} else {
   ////Code/Message for failer
}}}

CodePudding user response:

Worked out the fix:

The api is a python function on google cloud functions (the method would probably differ for different APIs)

You need to add the following code at the start and end of the function to accept a CORS request from flutter web.

def function(request):
    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE, HEAD',
            'Access-Control-Allow-Headers': 'custId, appId, Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN, Access-Control-Allow-Origin',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*'
    }

    ------ SOME CODE THAT DOES SOMETHING ------

    return(output,200,headers)

  • Related