Home > Software design >  How to solve Error: XMLHttpRequest error. in Flutter Web
How to solve Error: XMLHttpRequest error. in Flutter Web

Time:05-26

I want to use to Google places api and I am trying to call this api but I am getting this. error

Error: XMLHttpRequest error.
static Future<List<Result>?> searchPlaces(context, String query) async {
    String mapApiKey = "API_KEY";
    String _host = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
    final url = '$_host?query=$query&key=$mapApiKey';
    //
    var response = await http.get(Uri.parse(url));
    print(response.body);
    //
    if (response.statusCode == '200') {
      GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
      return result.results!;
    } else
      return null;
  }
}

CodePudding user response:

I don't know which platform you are using, but I guess the solution would be to disable chrome web security.

If you are working on mac try the following steps

  • Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
  • Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
  • Find '--disable-extensions'
  • Add '--disable-web-security'

And if you are working on windows just search for how to disable web security for chrome

CodePudding user response:

We need to add token in headers

"Authorization": "Bearer "   _sessionToken,
  1. I have used uuid to create token.
  2. Use this url 'https://cors-anywhere.herokuapp.com' before your actual url e.g.
String baseUrl = 'https://cors-anywhere.herokuapp.com';
String actualUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
String finalUrl = "$baseUrl/$actualUrl";

static Future<List<Result>?> searchPlaces(context, String query) async {
    String mapApiKey = "YOUR_KEY_HERE";
    var _sessionToken = Uuid().v4();
    String _host =
        'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/textsearch/json';
    final url = '$_host?query=$query&key=$mapApiKey';
    //
    var response = await http.get(Uri.parse(url), headers: {
      "Access-Control-Allow-Origin": "*",
      "X-Requested-With": "XMLHttpRequest",
      "Authorization": "Bearer "   _sessionToken,
    });

    //
    GPlacesSearch result = GPlacesSearch.fromJson(jsonDecode(response.body));
    return result.results!;
  }
}
  • Related