'Can't do POST request to a dotnet web api using flutter web app

So when I try to do a POST request to a dotnet web API from flutter web using Dio package, I got this error after a while:

XMLHttpRequest error.

In Android, the post request hits the endpoint successfully, but not in flutter web.

Flutter POST request:

Future<Response<dynamic>> test(String email, String password) async {
    if (dio.httpClientAdapter is DefaultHttpClientAdapter) {
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (HttpClient client) {
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;
        return client;
      };
    }
    try {
      final response = await dio.post(('https://10.0.2.2:5001/users/sign-in'),
          data: {"email": email, "password": password},
          options: Options(headers: {
            HttpHeaders.contentTypeHeader: "application/json",
            HttpHeaders.accessControlAllowOriginHeader: "*",
          }));
      return response;
    } catch (e) {
      print(e);
    }
  }

I've read online that this could be an error related to CORS but I've already configured CORS in my API server and still not works:

API StartUp.cs (C#) Configure services:

services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });

Configure:

    app.UseCors();

Have someone had a similar issue? Am I configuring wrong the CORS in my API? Do think that using dart's http would be a better approach?



Solution 1:[1]

Change

https://10.0.2.2:5001/users/sign-in

to

https://localhost:5001/users/sign-in

localhost won't work on android

android converts 10.0.2.2 to localhost

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CodeRaptor