HTTP Post request from Flutter Web

1.8k views Asked by At

I have a function on Google Cloud Functions that I am trying to make a post request to in my Flutter web app. I tested a post request in Python and it worked with the following request:

params = {'input_key':'input_value'}
headers = {"Content-Type": "application/json"}
r = requests.post("https://us-central1-lucid-bond-261904.cloudfunctions.net/cloudFunction", data=jason.dumps(params), headers=headers)

But when I try to do the same request from my Flutter web app using the http package, I keep getting an XMLHttpRequest error. Here's my http request in my flutter web app

String path = "https://us-central1-lucid-bond-261904.cloudfunctions.net/cloudFunction";
Map params = {'input_key':'input_value'}
var response = await http.post(path, body: json.encode(params), headers: <String, String>{'Content-Type': 'application/json'});

I know it successfully triggers the cloud function, because the first thing I have the cloud function do is print 'hello' to the log. It seems to maybe be an error in the way I'm choosing the content-type. I read this thread that implies that the content type might be getting changed to "application/json; charset=utf-8", but the fix that they specified doesn't apply to Flutter Web because the dart io package doesn't work on Flutter Web. So how do I correctly specify the content type? Or is there a better flutter package to use for this situation?

The error thrown back in Flutter is:

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 264:20      get current
packages/http/src/browser_client.dart 84:22

And the error in my Cloud Function

line 99, in cloudFunction shop_name = inputs_dict['input_key'] TypeError: 'NoneType' object is not subscriptable

EDIT: Just tried doing the same post request from Postman and it worked successfully. Still not working from my flutter app though. Do I need to enable CORS or something in the Google Cloud Function?

1

There are 1 answers

2
Rushwin Jamdas On BEST ANSWER

I finally made it work. In my cloud function, request.get_json() was returning null. When I added the paramter force=True, it finally worked. I didn't have to do force=True when trigger the function through python or postman, but for some reason triggering it through flutter required the force=true.

request.get_json(force=True)