I'm trying to call my Google Cloud Function using a Jquery request. This is blocked by the browser because of the CORS policy. To overcome this I tried what is described in the docs of Google Cloud functions: https://cloud.google.com/functions/docs/writing/http#handling_cors_requests. It says that CORS can be enabled using a preflight request.
To be precise, these are the first lines of my Cloud function:
def hello_world(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
"""
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
# Set CORS headers for the main request
headers = {
'Access-Control-Allow-Origin': '*'
}
I call the cloud function from my local client http://127.0.0.1:5000.
This is how I try to call the API, by first doing the preflight request and after that the actual API call:
$(function () {
console.log("starting preflight");
$.ajax({
url: "https://cloudfunction/recommend",
type: "OPTIONS"
}).always(function () {
console.log("preflight done");
$.post("https://cloudfunction/recommend", {
"some": "data"
}).done(function (data) {
alert("Data Loaded: " + data);
});
});
});
The preflight request seems to go well, however Chrome returns this error on the actual API (post) call: "Access to XMLHttpRequest at 'https://cloudfunction/recommend' from origin 'http://127.0.0.1:5000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
I already tried setting 'Access-Control-Allow-Origin': '*' and 'Access-Control-Allow-Methods': '*', and combinations, but all resulted in the same error as above.
Does someone know what is going wrong here?