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

63,252

Solution 1

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'

Solution 2

Using Osman Tuzcu's answer, I created flutter_cors to make the process easier.

Solution 3

run/compile your Flutter web project using web-renderer. This should solve the issue both locally and remotely:

flutter run -d chrome --web-renderer html
flutter build web --web-renderer html

Solution 4

Server side engine like node js or django is really needed to work with flutter web with bunch of external apis. Actually there's high possibility of same CORS error when we try to use internal api because of the CORS mechanism related to port number difference.

There are bunch of steps and answers from SO contributors that recommend to use chrome extensions to avoid CORS errors, but that is actually not cool for users. All the users should download the browser extensions to use the single website from us, which wouldn't be there if we used true server engines.

CORS is from browser as far as i know, so our flutter ios and android apps with same api code don't give those CORS errors. First time i encountered this error with flutter web, i believed i can deal with CORS in my app code lines. But that is actually not healthy way for users and long term dev plans.

Hope all flutter web newbies understand that web is quite a wild field for us. Even though i'm also newbie here, i highly recommend all the flutter web devs from 1.22.n stable to learn server side engines like node js. It is worth try.

And if u came so far down to this line of my self-answer, here's a simple guide for flutter web with node js. Flutter web is on stable channel but all those necessary infra are not fully ready for newbies like me. So be careful when you first dive into web field, and hope you re-check all the conditions and requirements to find out if you really need web version of your flutter app, and also if you really need to do this work with flutter. And my answer was yes lol

https://blog.logrocket.com/flutter-web-app-node-js/

Solution 5

I think disabling web security as suggested will make you jump over the current error for now but when you go for production or testing on other devices the problem will persist because it is just a workaround, the correct solution is from the server side to allow CORS from the requesting domain and allow the needed methods, and credentials if needed.

Share:
63,252

Related videos on Youtube

tsitixe
Author by

tsitixe

PETU, team exit

Updated on July 05, 2022

Comments

  • tsitixe
    tsitixe almost 2 years

    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 stackoverflow answers explained how to solve the CORS issue with serverside 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 was 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!! Thank you for reading [:

    • Sergey Metelin
      Sergey Metelin over 3 years
      In this case, I think you should enable it on the server-side. Have you tried ngrok to serve your app to see if it works that way? Maybe it's the server that doesn't allow localhost.
    • tsitixe
      tsitixe about 3 years
      This was baby question. Now i know why web devs pressed thumb down for my question. i added simple node js following medium articles with keywords 'flutter with node js' and it worked perfectly. We need server side add-ons to make flutter web work with those apis. Hope web newbies from flutter 1.22.n understand that we really need server like node engines to work with flutter web's apis
    • JLarana
      JLarana almost 3 years
      This could be the solution you are looking for stackoverflow.com/a/37765371/13758642
  • SIMMORSAL
    SIMMORSAL almost 3 years
    So what do we do when you use Firebase as the backend and still get the error?!
  • tsitixe
    tsitixe almost 3 years
    @SIMMORSAL i'm not pretty sure of what your Firebase-related error is. I've not gotten myself that far away combining node js engine and Firebase products. But if you've actually got through the error in a certain situation, then a new SO thread might be open with tags like flutter-web, cors, firebase, and firebase-<product-name>, and would be grateful if you comment the new thread's link here [:
  • SIMMORSAL
    SIMMORSAL almost 3 years
    I figured out the problem stackoverflow.com/a/67830000/4457315 ... Thaanks anyways.
  • Becca
    Becca almost 3 years
    This works. thank you but I am getting this warning "You are using an unsupported comment-line... Stability and security will suffer.", should I be worried?
  • Virtu_Acad
    Virtu_Acad almost 3 years
    This got the job done, thanks very much. After days of painful search and googling.
  • Osman Tuzcu
    Osman Tuzcu almost 3 years
    Don't worry @Becca because this works only your local without cors.
  • xjcl
    xjcl over 2 years
    For Linux me the file was at ~/snap/flutter/common/flutter/packages/flutter_tools/lib/src‌​/web/chrome.dart BTW
  • xjcl
    xjcl over 2 years
    And the other file: sudo rm ~/snap/flutter/common/flutter/bin/cache/flutter_tools.stamp
  • Efx
    Efx over 2 years
    I also wanted to know, how the hell did your find this solution? It worked for me!
  • Youcef EL KAMEL
    Youcef EL KAMEL over 2 years
    Hello really nice solution but at every flutter upgrade I will have to that to do a simple http call ? :'(
  • bradpotts
    bradpotts over 2 years
    plus 1 for solving my problem going around in circles thinking it was something else thanks
  • markhops
    markhops over 2 years
    This saved my life. Thank you!
  • WDR
    WDR over 2 years
    I did it but didn't work. When I try to launch the Chrome web it creates flutter_tools.stamp again.
  • Sahid rahutomo
    Sahid rahutomo over 2 years
    :( when deploying to production, its showing error again
  • Taleb
    Taleb over 2 years
    Not worked for me :(, I also got "XMLHttpRequest" !!!
  • Sahid rahutomo
    Sahid rahutomo over 2 years
    use this command for production flutter build web --web-renderer html
  • Leonid Veremchuk
    Leonid Veremchuk over 2 years
    @Sahid rahutomo This is not solution. Do you know how to works html render?
  • tsitixe
    tsitixe over 2 years
    cool! Thanks [:
  • Ven Shine
    Ven Shine over 2 years
    It works for me, thanks
  • Admin
    Admin about 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
  • scienticious
    scienticious about 2 years
    Not working on released flutter web build
  • scienticious
    scienticious about 2 years
    Not working on remotely
  • scienticious
    scienticious about 2 years
    Does it work on released web build of flutter?
  • RobDil
    RobDil about 2 years
    For your production app you will have to set appropriate CORS headers on your files.
  • Golden Lion
    Golden Lion about 2 years
    I received a message the feature was not supported.
  • cosbor11
    cosbor11 about 2 years
    No active package flutter_cors.
  • Rexios
    Rexios about 2 years
    @cosbor11 You must activate the package with dart pub global activate not flutter pub global activate
  • Koen Van Looveren
    Koen Van Looveren about 2 years
    Does not seem to work for me. Probably because I am using fvm for flutter version management
  • Rexios
    Rexios about 2 years
    @KoenVanLooveren It definitely works with fvm. If you want to patch a flutter version that isn't the one you have set as global, then you need to pass in the path to it.
  • Koen Van Looveren
    Koen Van Looveren about 2 years
    That is what I did. I just fixed my cors settings on the server directly. That fixed it
  • Kavin D
    Kavin D about 2 years
    This helps to me. this works. Thanks for your contribution @Rexios
  • Abanoub Istfanous
    Abanoub Istfanous about 2 years
    Not working on released flutter web build –
  • Abanoub Istfanous
    Abanoub Istfanous about 2 years
    @scienticious have you found any solution for web build ??
  • user10033434
    user10033434 about 2 years
    Your package works... many thanks...
  • THEODORE
    THEODORE almost 2 years
    works like magic am very grateful thank thank
  • Pramod
    Pramod almost 2 years
    'flutter_cors' is not recognized as an internal or external command In WINDOWS
  • Pramod
    Pramod almost 2 years
    I thought this solution isn't working for me. but then I noticed I hadn't put a comma after --disable-web-security