[英]Google Cloud Function: Python and CORS
誰能告訴我我做錯了什么,我一直在閱讀 Google Cloud Functions 文檔,但這對我來說沒有意義......
這是文檔的鏈接: https://cloud.google.com/functions/docs/writing/http#functions_http_cors-python
這是代碼:
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)
當我嘗試從前端表單發送 POST 請求時 - 我收到以下錯誤:
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.
老實說,我不明白我錯過了什么/做錯了什么……我也覺得我可能把事情復雜化了。
為了完成這個循環,這里是 POST 請求的 JS 代碼:
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)
}
});
您if
else
。
所以你的第二個headers =
block 總是那個被設置的。 第二個分配不是將這些標頭附加到數據中,而是完全重新分配變量。 所以你沒有在那里得到訪問源頭。
測試它以驗證的方法是在第二次分配之后放置一個print(headers)
以查看發生了什么。
編輯:在 OPTIONS 案例的 if 塊中缺少返回。
感謝@Gabe Weiss——
我意識到我需要做三件事......
首先,我在if request.method == 'OPTIONS':
語句的末尾添加了return ('', 204, headers)
。
其次,我將請求調用移至設置標題后。 最后,我返回了響應
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.