Search code examples
flutterdarthttprequest

How to solve flutter web api cors error only with dart code?


It seems like CORS error is well-known issue in the web field. But I tried flutter web for the first time ever and I faced critical error.

The code below worked well in app version when it was running on iOS device, but when i tested the same code on Chrome with web debugging from beta channel, it encountered CORS error.

Other Stack Overflow answers explained how to solve the CORS issue with server-side files of their projects, but I have totally no idea what is server thing and how to deal with their answers. The error message from Chrome console is below:

[ Access to XMLHttpRequest at 'https://kapi.kakao.com/v1/payment/ready' from origin
'http://localhost:52700' 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. ]

So, what I want to do is to solve above 'Access-Control-Allow-Origin header' issue ONLY WITH DART CODE! Code below is what I've tried to solve these issues only with my main.dart.

onPressed: () async {
      var res =
          await http.post('https://kapi.kakao.com/v1/payment/ready', encoding: Encoding.getByName('utf8'), headers: {
        'Authorization': 'KakaoAK $_ADMIN_KEY',
        HttpHeaders.authorizationHeader: 'KakaoAK $_ADMIN_KEY',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "POST, GET, OPTIONS, PUT, DELETE, HEAD",
      }, body: {
        'cid': 'TC0ONETIME',
        'partner_order_id': 'partner_order_id',
        'partner_user_id': 'partner_user_id',
        'item_name': 'cool_beer',
        'quantity': '1',
        'total_amount': '22222',
        'vat_amount': '2222',
        'tax_free_amount': '0',
        'approval_url': '$_URL/kakaopayment',
        'fail_url': '$_URL/kakaopayment',
        'cancel_url': '$_URL/kakaopayment'
      });
      Map<String, dynamic> result = json.decode(res.body);
      print(result);
    },

Even though I actually had the header "Access-Control-Allow-Origin": "*" which most other answers recommended, the Chrome console printed same error message. Weird thing is that the same code made successful request in mobileApp version. So I think this is only problem with flutter WEB VERSION.

Hope somebody can figure it out and suggest only-dart code to resolve the issue in my main.dart!


Solution

  • 1- Go to flutter\bin\cache and remove a file named: flutter_tools.stamp

    2- Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.

    3- Find '--disable-extensions'

    4- Add '--disable-web-security'