'Flutter web CORS issue

I am using flutter-web with .net webapi. To shoot my requests, I have tried Dio and Dart HTTP packages. Neither of the two have worked because of CORS issue. Kindly tell me what am I doing wrong. is there a way to get around this problem ? There is no problem with api when it comes to shoot them from postman .

Sample code

I have added var cors = new EnableCorsAttribute("", "", "*"); config.EnableCors(); in webapi as well.

Flutter HTTP Requests first of the two is built on dio.

Dio dio= new Dio();
  Future postData2(user) async{
    debugPrint(user.toString());
    dynamic data = {
    'phone_number': user['country_code'] + user['phone_number'],
    'password':user['password']
    };
    final String pathUrl = "http://localhost:62435/api/Token/GetToken";
    var response = await dio.post(pathUrl, data:data, options: Options(
        headers: {
          'content-type': 'application/json',
          'Access-Control-Allow-Origin':'true'
        },
    ));
    return response.data;
  }

//Http : dart

  Future postData(user) async{
    dynamic data = {
      'phone_number': user['country_code'] + user['phone_number'],
      'password':user['password']
    };
    final String pathUrl = "http://localhost:62435/api/Token/GetToken";
    dynamic response = _http.post(
      pathUrl,
      body : data,
      headers : {
        HttpHeaders.contentTypeHeader : 'application/json',
        //'Access-Control-Allow-Origin':'true'
      }
    );
    debugPrint( //response.statusCode +
        " " + response.data.toString());
  }

For dio, at least the checkup request is sent enter image description here

enter image description here

enter image description here

with Dio I get following errors.

Dio Request headers in network tab. The request remains pending. and does not finish.

Request URL: http://localhost:62435/api/Token/GetToken
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Access-Control-Allow-Origin: true
content-type: application/json; charset=utf-8
Referer: http://localhost:63440/
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
{phone_number: "123124", password: "safaSF"}


Solution 1:[1]

When you are using Flutter Web and call an API, Flutter uses:
Preflight request (before call the API)

It is a request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers.
It is an OPTIONS request, using three HTTP request headers:

1.Access-Control-Request-Method,
2.Access-Control-Request-Headers,
3.and the Origin header.

In that case you need to check if your API is allowed for methods OPTIONS.

Access-Control-Allow-Origin: https://foo.bar.org
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE

If your API not accept, you need to configurare your response to send OPTIONS in
Access-Control-Allow-Methods for example:

Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Request-Headers: origin, x-requested-with
Origin: https://foo.bar.org

More details in Mozilla Glossary

Solution 2:[2]

From the comments above I assume you are using ASP .net web api. If this is the case, then you should perhaps use the constructor for EnableCorsAttribute properly. As per the documentations here, you have to use the first parameter in the constructor to pass allowed list of origins. In your case you can do either of the following.

Allow all origins

public EnableCorsAttribute(
    "*",
    "*",
    ""
)

Allow specific origins

public EnableCorsAttribute(
    "http://localhost:59789,http//localhost:another_port,http://example_domain.com",
    "*",
    ""
)

Also note that Access-Control-Allow-Origin is response header. You should not set it in your request headers. Its tells the browser or the client from which origins are allowed to access the server. Read more about CORS here.

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 linhadiretalipe
Solution 2