Flutter web CORS issue

10,607

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

Share:
10,607
S P
Author by

S P

Updated on June 04, 2022

Comments

  • S P
    S P almost 2 years

    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"}
    
    • Abhilash Chandran
      Abhilash Chandran over 3 years
      Access to XMLHttpRequest at 'http://localhost:62435/api/Token/GetToken' from origin 'http://localhost:59789' This line in the error log tells you that you are doing cross domain request. Hence its not getting through you should add the http://localhost:59789 in the server side as one of allowed origins. However in usual cases for testing in postman this will work because its not from another web domain. For testing purpose in the server side you can allow all domains using a * in the server side. If you provide the which server you are using we can find how to configure for the server.
    • S P
      S P over 3 years
      Hi Abhilash, ive tried var cors = new EnableCorsAttribute("", "", "*"); config.EnableCors(); in webapi.
    • S P
      S P over 3 years
      this is my new request Future postData(user) async{ dynamic data = {'phone_number': user['country_code'] + user['phone_number'],'password':user['password']}; final String pathUrl = "localhost:62435/api/Token/GetToken"; print(jsonEncode(data)); dynamic response = _http.post(pathUrl,body : jsonEncode(data),headers : {HttpHeaders.contentTypeHeader : 'application/json','Access-Control-Allow-Origin':'true'}); if (response.statusCode == 200) { return response; } else { throw Exception('Failed to load '); } }
    • Abhilash Chandran
      Abhilash Chandran over 3 years
      Now you have removed the old error. Does this mean its a new error? Did you try my suggested answer.?
    • S P
      S P over 3 years
      This one was a new error at the time. Your suggestions were right. after a while this issue was solved. I will post solution soon.