dart-lang / http

A composable API for making HTTP requests in Dart.
https://pub.dev/packages/http
BSD 3-Clause "New" or "Revised" License
1.01k stars 345 forks source link

Flutterweb: HTTP error with localhost. #660

Open SittiphanSittisak opened 2 years ago

SittiphanSittisak commented 2 years ago

I am trying to connect API with HTTP. When I use a URL from the host, it works. But when I use a URL from localhost by the xampp, it will error. The error is "FormatException: SyntaxError: Unexpected token < in JSON at position 0". The URL from host and localhost can be used in The Postman.

basic code: import 'package:http/http.dart' as HTTP; Map<String,dynamic> data = ???; String url = ???; var uri = Uri.parse(url); var response = await http.post(uri, body: data) responseDecoded = json.decode(response.body); print('response ---> $responseDecoded');

flutter doctor: Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, 2.5.0, on Microsoft Windows [Version 10.0.19042.1466], locale th-TH) [√] Android toolchain - develop for Android devices (Android SDK version 30.0.3) [√] Chrome - develop for the web [√] Android Studio (version 2020.3) [√] VS Code (version 1.63.2) [√] Connected device (2 available)

• No issues found!

Thank you.

SittiphanSittisak commented 2 years ago

I try https://192.168.0.1/ and https://10.0.0.1/ instead of http://127.0.0.1/ but it didn't work for me.

pshreyam commented 2 years ago

I too tried with CORS and other settings in django but to no avail. Could anyone suggest me how to use flutter http with localhost? (Preferably with django-rest-framework)

pshreyam commented 2 years ago

I figured out how to work with django rest framework and flutter http. There was some issues related to the CORS. I has developed the wrong concept that the CORS settings are to be implemented in the client side (flutter) whereas it was the backend that required the CORS settings.