Because I have been getting some unexpected CORS errors in my browser console for the past few weeks, I have set up a super simple Python script with a single function inside Google Cloud Functions:
def prepData(request):
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
headers = {
'Access-Control-Allow-Origin': '*'
}
return ("", 200, headers)
It looks very similar to the function presented by Google on their documentation page with one major difference: I am using POST rather than GET.
When calling the function, I am seeing a success message (Function execution took 13 ms, finished with status code: 200) in around 50% of cases and a connection error (Function execution took 11 ms, finished with status: 'connection error') in all other cases. Whenever I am getting a connection error inside GCF, Chrome's console logs an error: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am currently considering three possible causes:
- GCP Infrastructure. I have found some related questions where Google was acknowledging some infrastructure issues.
- Python error
- CORS error (user sideshowbarker says: very unlikely)
What is the cause of the issue and how do I fix it?
Here is the JS code that calls the Python script:
const xhr = new XMLHttpRequest();
xhr.open("POST", "[URL]");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(stringified_serialized_data);
Edit on 4/2/20:
I have discovered a way to not trigger the error: Add some code between the two return statements. I have not yet figured out what kind of code is needed, but d = request.get_json() appears to be sufficient. The new code looks as follows:
def prepData(request):
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
d = request.get_json() #THIS LINE IS NEW
headers = {
'Access-Control-Allow-Origin': '*'
}
return ("", 200, headers)