skip to Main Content

I try to call a google cloud function from flutter using POST, but it always returns 415.

This is the call:

    http
        .post(
      Uri.parse('https://example.com/function'),
      headers: <String, String>{
        'content-type': 'application/json'
      },
      body: jsonEncode(<String, String>{
        "message": "test",
        "version": "1",
      }),
      encoding: Encoding.getByName('utf-8'),
    )

The google cloud function is set up correctly, I can call it successfully with curl

curl -X POST https://example.com/function --data '{"message": "test", "version": 1}' -H "Content-Type: application/json"

Edit:
This is the google cloud function:

import functions_framework


# Register an HTTP function with the Functions Framework
@functions_framework.http
def my_http_function(request):
    # Your code here

    print(request)

    # Return an HTTP response
    return "OK"

which is deployed like this:

gcloud functions deploy example-func 
--gen2 
--runtime=python311 
--region europe-west3 
--source=. 
--entry-point=my_http_function 
--trigger-http 
--allow-unauthenticated

As the curl post works, the function seems to work fine and as expected.

Edit 2:

This happens from flutter web. I found some hints, that CORS might be the issue and adding Access-Control-Allow-Origin: * to the header would solve it, but it didn’t.

What is the problem?

2

Answers


  1. You should send json and accept json in the header instead:

    headers: {
      "Content-Type": "application/json; charset=UTF-8",
      "Accept":"application/json",
    },
    

    Updated: CORS

    Access-Control-Allow-Origin: *
    Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
    Access-Control-Allow-Headers: Content-Type
    

    Reference:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    Login or Signup to reply.
  2. Try the below:

    
        http.post(
          Uri.parse('https://example.com/function'),
          headers: <String, String>{
            "Content-Type": "application/json",
            "Accept": "application/json"
          },
          body: {
            "message": "test",
            "version": "1",
          },
        )
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search