wahyu
wahyu

Reputation: 2405

How to handle cors for web flutter

I have been struggle to fix the cors problem in my PWA project of flutter and I am following this

how to solve flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request?.

I am using universal_io package since dart.io can not be used for web...here is the part of the code

HttpClient client = new HttpClient();
      client.badCertificateCallback =
          ((X509Certificate cert, String host, int port) => true);
      String url = 'https:xxxx.php';
      Map map = {
        "a": "a",
        "b": "b"
      };
      HttpClientRequest request = await client.postUrl(Uri.parse(url));
      request.headers.set('content-type', 'application/json');
      request.add(utf8.encode(json.encode(map)));
      if (request is BrowserHttpClientRequest) {
        request.credentialsMode = BrowserHttpClientCredentialsMode.include;
      }
      HttpClientResponse response = await request.close();
      print(response.toString());
      String reply = await response.transform(utf8.decoder).join();
      print(reply);

but I get the error that say like this

--------------------------------------------------------------------------------
BrowserHttpClient received an error from XMLHttpRequest (which doesn't tell
reason for the error).
HTTP method:        POST
URL:                https://www.rscm.co.id/apirscm/v2.php
Origin:             http://localhost:64121
Cross-origin request!
XmlHttpRequest 'credentials mode' is enabled.
Did the server send the following mandatory headers?
  * Access-Control-Allow-Credentials: true
  * Access-Control-Allow-Origin: http://localhost:64121
    * In credentials mode, '*' would fail!
  * Access-Control-Allow-Methods: POST

is there a way to solve this problem?

Upvotes: 1

Views: 4859

Answers (2)

Boris Kamtou
Boris Kamtou

Reputation: 492

you can do something like thisto enable credentials mode:

final httpClientRequest = MyHttpClientRequest;
if (httpClientRequest is BrowserHttpClientRequest) {
  httpClientRequest.credentialsMode = BrowserHttpClientCredentialsMode.include;
}

But prefer using this librairy universal_io instead of dart.io

Upvotes: 1

hiashutoshsingh
hiashutoshsingh

Reputation: 1020

You can you local host server in the debug mode of chrome, here is how: open this in terminal.

open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/Users/i0868/Desktop/Chrome" --disable-web-security

Upvotes: 2

Related Questions