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
You should send json and accept json in the header instead:
Updated: CORS
Reference:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Try the below: