user17560050
user17560050

Reputation:

Flutter web http Error: XMLHttpRequest error

I've been struggling with an http request issue when I try to perform a simple post request to a .net backend. The backend has CORS set up and I've been through many stack overflow posts, trying to solve this issue but it still gives me the same error. Everything works when I test the API on SwaggerUI (same as postman). I don't get it. Is there something I am missing here? Thank you.

The code:

import 'dart:convert';
import 'package:http/http.dart' as http;

abstract class ParentRemoteDataSource {
  Future<void> create({required Map<String, dynamic> parent});
}

class ParentRemoteDataSourceImpl implements ParentRemoteDataSource {
  final http.Client _client = http.Client();
  final String _url = "http://localhost:5000/api/member/create";

  @override
  Future<void> create({required Map<String, dynamic> parent}) async {
    final Uri uri = Uri.parse(_url);
    final Map<String, String> headers = {"Content-Type": "application/json"};

    final http.Response response = await _client.post(
      uri,
      headers: headers,
      body: jsonEncode(parent),
    );
    print(response.body);
  }
}

The code above executes at the press of a button on the UI part. The error from the post request reads: ERR_CERT_AUTHORITY_INVALID , and below that reads: Uncaught (in promise) Error: XMLHttpRequest error.

Upvotes: 0

Views: 885

Answers (1)

Maikzen
Maikzen

Reputation: 1624

You can avoid that error this way:

Create a custom httpOverrides:

class MyHttpOverrides extends HttpOverrides{
  @override
  HttpClient createHttpClient(SecurityContext context) {
    return super.createHttpClient(context)
      ..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
  }
}

And then override the main:

void main() async {
  HttpOverrides.global = new MyHttpOverrides();
...

Upvotes: 0

Related Questions