Flutter web http CORS issue - flutter

I am developing a web application with flutter. The http requests are made with flutter http plugin. The requests were working fine before. Recently I am getting a CORS Error like this
Access to XMLHttpRequest at 'https://www.google.com/' from origin 'http://localhost:33121' 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.
I've added corresponding headers with my request. Even that didn't help me to figure it out.
I am sharing the code snippet that I've used for testing.
`var client = http.Client();
try {
var url = 'https://www.google.com/';
var response = await http.get(Uri.parse(url));
print(response.body);
print(response.statusCode);
} finally {
client.close();
}`
These are logs that I am getting from the browser console
Access to XMLHttpRequest at 'https://www.google.com/' from origin 'http://localhost:33189' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
www.google.com/:1 Failed to load resource: net::ERR_FAILED
errors.dart:299 Uncaught (in promise) Error: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 963:28 get current
packages/http/src/browser_client.dart 69:22
dart-sdk/lib/async/zone.dart 1653:54 runUnary
dart-sdk/lib/async/future_impl.dart 147:18 handleValue
dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback
dart-sdk/lib/async/future_impl.dart 795:13 _propagateToListeners
dart-sdk/lib/async/future_impl.dart 557:7 [_complete]
dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue
dart-sdk/lib/async/stream.dart 1587:7
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14 _checkAndCall
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39 dcall
dart-sdk/lib/html/dart2js/html_dart2js.dart 37341:58
I've tried adding these header information with my request. But this also didn't work.
`var client = http.Client();
try {
var url = 'https://www.google.com/';
var response = await http.get(
Uri.parse(url),
headers: <String, String> {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,PUT,OPTIONS",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
},
);
print(response.body);
print(response.statusCode);`

flutter run -d chrome --web-renderer html
docs https://docs.flutter.dev/development/platform-integration/web/renderers

Related

Error: XMLHttpRequest error. Flutter in Http Package

When fetching anything from internet using http package it show error Error: XMLHttpRequest error. Flutter in Http Package Error in web only
var companyLogoResponse = await http.get(
Uri.parse(
"https://stock.znindia.com/assets/assets/logo.png"),
);
var companyLogo = companyLogoResponse.bodyBytes;
For Show image in PDF
Container(
padding: const EdgeInsets.all(4),
height: 100,
width: 100,
child: Image(MemoryImage(companyLogo),
fit: BoxFit.fitWidth),
),
When Code Run it show
Error: XMLHttpRequest error.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 299:10 createErrorWithStack
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 341:28 _throw
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/core/errors.dart 116:5 throwWithStackTrace
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1378:11 callback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15 <fn>
It's a cross-orgin issue, If you have access over backend just add the below lines in your api call
headers: {
"Access-Control-Allow-Origin": "*"
}
If the above method does not works try this library
flutter_cors: ^1.3.2
And finally a temporary solution
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en
install this chrome extension

How to whiltlist local host - how to Firebase https request restrictions on flutter web

I'd like to download the JSON file which can be accessed by this url https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media. Every time I call the function I get a Error: XMLHttpRequest error. After some researches I found that this might be beacuase Google Firebase Storage is blocking it. Does anybody know how to avoid this block? I've read that I should whiltlist my local host? But how?
headers: {
HttpHeaders.authorizationHeader: 'Basic your_api_token_here', //here i want my token
},
But I have no clue how to get my api Token. Does anybody know how to fetch this token? May this error be caused becaus I run it on chrom flutter?
import 'package:http/http.dart' as http;
void testFunction(){
var url_string = "https://firebasestorage.googleapis.com/v0/b/prufungssimulation-caff9.appspot.com/o/5qPfjoZjdNXyN5Ob2q3pFbj5MKy1.json?alt=media";
var result = await getJsonFromFirebaseRestAPI(url_string);
print(result);
}
Future<String> getJsonFromFirebaseRestAPI(String url) async {
http.Response response = await http.get(Uri.parse(url));
return response.body;
}
The JSON file result should look like this:
routes: []
It's basically empty I'm just trying to implement the function.
I use http: ^0.13.5
I get the following error:
Error: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 299:10
createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 341:28
_throw
dart-sdk/lib/core/errors.dart 116:5
throwWithStackTrace
dart-sdk/lib/async/zone.dart 1378:11
callback
dart-sdk/lib/async/schedule_microtask.dart 40:11
_microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5
_startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15
<fn>
``
Can anybody solve my issue?
Appreciate your time :)

Flutter rest api https calling

final url ="https://example.com/auth/individual/login";
final response = await http.post(
Uri.parse(url),
body: {"email": 'c#gmail.com', 'password': 'C#123'});
print('Response body: ${response.body}');
print(await http.read(Uri.parse('https://example.com/auth/individual/login')));
error:
Response body: {"message":"Cannot read property 'password' of null"}
Error: Request to https://example.com/auth/individual/login failed with status 404: Not Found.
at Object.throw_ [as throw] (http://localhost:50754/dart_sdk.js:5063:11)
at browser_client.BrowserClient.new.[_checkResponseSuccess] (http://localhost:50754/packages/http/src/multipart_request.dart.lib.js:618:17)
at browser_client.BrowserClient.new.read (http://localhost:50754/packages/http/src/multipart_request.dart.lib.js:581:36)
at read.next (<anonymous>)
at http://localhost:50754/dart_sdk.js:40192:33
at _RootZone.runUnary (http://localhost:50754/dart_sdk.js:40062:59)
at _FutureListener.thenAwait.handleValue (http://localhost:50754/dart_sdk.js:34983:29)
at handleValueCallback (http://localhost:50754/dart_sdk.js:35551:49)
at Function._propagateToListeners (http://localhost:50754/dart_sdk.js:35589:17)
at _Future.new.[_completeWithValue] (http://localhost:50754/dart_sdk.js:35437:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:50754/dart_sdk.js:35458:35)
at Object._microtaskLoop (http://localhost:50754/dart_sdk.js:40330:13)
at _startMicrotaskLoop (http://localhost:50754/dart_sdk.js:40336:13)
at http://localhost:50754/dart_sdk.js:35811:9
I changed the api link to example.com this:
https://example.com/auth/individual/login
In your body, try putting password in double quotes rather than single. I don't think many backends will accept keys with single quotes as it is not valid JSON.

Flutter/ get PDF file from URL

void getFileFromUrl(String uri) async {
var fileName = 'testonline';
try {
var _uri = Uri.parse(uri);
var data = await http.get(_uri);
var bytes = data.bodyBytes;
var dir = await getApplicationDocumentsDirectory();
File file = File("${dir.path}/" + fileName + ".pdf");
print(dir.path);
File urlFile = await file.writeAsBytes(bytes);
_pdfController = PdfController(document: PdfDocument.openFile(dir.path));
} catch (e) {
throw Exception("Error opening url file");
}
}
Hello I am developing website with Flutter,
I would like to present PDF file on my website.
getFileFromUrl(
'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');
I am calling this function in inistate on my web site, this link is the testing pdf link which is valid link.
But I am getting this error.
Error: Exception: Error opening url file
at Object.throw_ [as throw] (http://localhost:58701/dart_sdk.js:5037:11)
at membership_agreement_screen._MembershipAgreementScreenState.new.getFileFromUrl
(http://localhost:58701/packages/clio_application_portal/screens/membership_agreement_screen.dart.lib.js:1312:23)
at getFileFromUrl.throw (<anonymous>)
at http://localhost:58701/dart_sdk.js:37379:38
at _RootZone.runBinary (http://localhost:58701/dart_sdk.js:37249:59)
at _FutureListener.thenAwait.handleError (http://localhost:58701/dart_sdk.js:32511:48)
at handleError (http://localhost:58701/dart_sdk.js:33044:51)
at Function._propagateToListeners (http://localhost:58701/dart_sdk.js:33070:17)
at _Future.new.[_completeError] (http://localhost:58701/dart_sdk.js:32920:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:58701/dart_sdk.js:32956:31)
at Object._microtaskLoop (http://localhost:58701/dart_sdk.js:37497:13)
at _startMicrotaskLoop (http://localhost:58701/dart_sdk.js:37503:13)
at http://localhost:58701/dart_sdk.js:33274:9
Please let me know what is wrong...
I am waiting for you help..
Thanks for reading.
I would assume the problem is that this is a cross origin call, which is not allowed in a website. This has nothing to do with flutter though. But is a security feature enforced by the browsers.
If you want to serve some pdf file from another host than you are serving the JavaScript you have to either have control over the server hosting the PDF to add CORS headers, or add a reverse proxy on the same host of your JavaScript which proxies all requests.
Flutter describs this problem for images, but it just as well effects any http connections: https://flutter.dev/docs/development/platform-integration/web-images#cross-origin-images

dio put operation not working in fllutter

Im trying to connect flutter web app with mongodb using restheart api. PUT operation is required for creating new collection in mongoDB. I checked request in Postman, its works fine. I can get data from already existing collection (GET, POST works fine).
Code:
Dio dio = new Dio();
dio.interceptors.add(InterceptorsWrapper(onRequest:
(RequestOptions options) async {
var customHeaders = {
'content-type': 'application/json',
HttpHeaders.authorizationHeader: "Basic $encoded"
};
options.headers.addAll(customHeaders);
return options;
}));
String url = "http://localhost:8080/toofo";
response2 = await dio.put(url);
print("############## ${response2.statusCode} ##########");
print("############## ${response2.data} ##########");
Error:
Error: DioError [DioErrorType.RESPONSE]: XMLHttpRequest error.
at Object.throw_ [as throw] (http://localhost:52789/dart_sdk.js:4773:11)
at dio_for_browser.DioForBrowser.new.<anonymous> (http://localhost:52789/packages/dio/src/entry/dio_for_browser.dart.lib.js:359:27)
at Generator.next (<anonymous>)
at onValue (http://localhost:52789/dart_sdk.js:35655:33)
at _RootZone.runUnary (http://localhost:52789/dart_sdk.js:35540:58)
at _FutureListener.thenAwait.handleValue (http://localhost:52789/dart_sdk.js:30956:29)
at handleValueCallback (http://localhost:52789/dart_sdk.js:31466:49)
at Function._propagateToListeners (http://localhost:52789/dart_sdk.js:31498:17)
at _Future.new.[_completeWithValue] (http://localhost:52789/dart_sdk.js:31357:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:52789/dart_sdk.js:31377:35)
at Object._microtaskLoop (http://localhost:52789/dart_sdk.js:35756:13)
at _startMicrotaskLoop (http://localhost:52789/dart_sdk.js:35762:13)
I also tried http package in flutter, got similar error.
This is the postman's status of PUT request 201Created
XMLHttpRequest error occurs for cross origin. Use this hearder
headers: {
'content-type': 'application/json',
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
"Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
"Access-Control-Allow-Methods": "POST, OPTIONS"
},