Reputation: 507
Can someone tell me what I am doing wrong, I have been reading the Google Cloud Functions documentation but it is not making sense to me...
Here's the link to the documentation: https://cloud.google.com/functions/docs/writing/http#functions_http_cors-python
Here is the code:
import flask, json, logging, os, requests
from requests.exceptions import HTTPError
def get_accesstoken():
try:
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
authUrl = f"{os.environ.get('AUTH_BASE_URI')}{os.environ.get('AUTH_ENDPOINT')}"
payload = {'client_id': os.environ.get("CLIENT_ID"), 'client_secret': os.environ.get("CLIENT_SECRET"), 'grant_type': os.environ.get("GRANT_TYPE")}
resp = requests.post(authUrl, data=json.dumps(payload), headers=headers)
return resp.json()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
return http_err
except Exception as err:
print(f'Other error occurred: {err}')
return err
def addrecord(request): ## <--- this is the entry cloud function
"""HTTP Cloud Function
Add records to ANY MC DataExtension
Args:
request (flask.Request): The request object.
<http://flask.pocoo.org/docs/1.0/api/#flask.Request>
----------------------------------------------------------------------------
data = request.get_json().get('data', [{}]) // JSON array of objects
dataId = request.get_json().get('dataId', None) // string
"""
request_json = request.get_json(silent=True)
token = get_accesstoken()
payload = request_json["data"]
dextUrl = f"{os.environ.get('REST_BASE_URI')}{os.environ.get('REST_DE_ENDPOINT')}{request_json['dataExtId']}/rowset"
# Set CORS headers for the preflight request
if request.method == 'OPTIONS':
# Allows GET & POST 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)
headers = {
'Content-type': 'application/json',
'Authorization': 'Bearer '+token["access_token"],
'Access-Control-Allow-Origin': '*'
}
resp = requests.post(dextUrl, data=json.dumps(payload), headers=headers)
return(resp.raise_for_status(), 200, headers)
When I try to send a POST request from my frontend form - I get the following error:
Access to XMLHttpRequest at 'https://xxxxxxxxxx.cloudfunctions.net/addrecord' from origin 'https://mywebsite.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.
I honestly do not understand what I am missing / doing wrong...I also feel like I may be over complicating things.
To complete the circle, here is the JS code that is doing to POST request:
let postData = {...};
$.ajax({
url: 'https://xxxxxxxxxx.cloudfunctions.net/addrecord',
type: 'post',
crossDomain: true,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(postData),
success: function (data) {
console.info(data);
},
error: function (data) {
console.log(data)
}
});
Upvotes: 2
Views: 821
Reputation: 507
Thanks to @Gabe Weiss --
I realized that I needed to do three things...
First, I added return ('', 204, headers)
to the end of the if request.method == 'OPTIONS':
statement.
Second, I moved my request call to after the headers were set. and Finally, I returned the response
Upvotes: 1
Reputation: 3342
You didn't else
your if
block that sets the headers.
So your second headers =
block is always the one that's getting set. The second assignment isn't appending those headers to the data, they're re-assigning the variable entirely. So you're not getting the access origin headers in there.
Way to test it to verify, is to put a print(headers)
after the second assignment to see what's going on.
Edit: Missing the return in the if block for the OPTIONS case.
Upvotes: 1