I have a simple cloud function in google cloud that receives data, and submits back a response after processing the data. I kept running into a CORS error, so tried with a simple Hello World as well.
Here’s client side code (obviously changed for privacy:
callCloudFunc();
function callCloudFunc(data) {
const url = 'https://{googe-location}.cloudfunctions.net/myCloudFunc';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(data),
mode: 'cors'
})
.then(response => response.json())
.then(data => {
console.log('Success:',data);
})
.catch((error) => {
console.error('Error:',error);
});
}
Here’s server side code in the google cloud func:
import functions_framework
import itertools
from collections import Counter
from flask import escape
import json
@functions_framework.http
def myCloudFunc(request):
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": "GET, 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": "*"}
try:
//some logic here...
return json.dumps(result), 200, headers
except json.JSONDecodeError:
return 'Invalid JSON format', 400, headers
I keep getting the following error in the browser:
Access to fetch at 'https://{google-location}.cloudfunctions.net/myCloudFunc' from origin 'https://console.cloud.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
You can replace ‘https://console.cloud.google.com’ with whatever site, doesn’t seem to work anywhere.
I tried the same call in postman and curl, and it works fine, even if I copy and paste the request in browser as curl and run in terminal or postman. It just doesn’t work in browser.
I also tired specifying a site, instead of the wildcard… so “Access-Control-Allow-Origin”: “mySite”… still doesn’t work in browser. Am I doing something wrong on the server or client side?
I ran in no-cors mode, still no luck.