[英]CORS error when trying to call Google Cloud function from the front-end (Web site)
當我嘗試從 Web 站點(前端)調用它時,我的谷歌雲 function 出現 CORS 問題。 問題是我可以在 Jupyter notebook 中成功執行相同的代碼而不會出錯。 到目前為止,我已經添加了啟用 CORS 訪問所需的所有內容,但我仍然遇到相同的錯誤(從來源“http://localhost:3000”訪問“https://****”處的 XMLHttpRequest已被 CORS 策略阻止:所請求的資源上不存在“訪問控制允許來源”header。有什么幫助嗎?
下面是源代碼:
import requests
import json
import flask
def myFunction(request):
request_json = request.get_json()
# preflight request
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
print ('', 204, headers)
# main request
headers = {
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
'Access-Control-Allow-Origin': '*'
}
# Call to get a access token from a refresh token
response = requests.post(url = "https://accounts.zoho.com/oauth/v2/...",headers = headers)
accessToken = response.json()['access_token']
# Call to zoho Api to insert a new lead
url = 'https://www.zohoapis.com/crm/v2/Leads'
v_access = 'Zoho-oauthtoken ' + accessToken
headers = {
'Authorization': v_access,
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,GET, POST'
}
json_data = request.get_json(silent=True)
newdata = json.dumps(json_data)
v_data = str(json.loads(newdata))
v_data1 = v_data.encode('utf-8')
post_response = requests.post(url,headers = headers, data = v_data1)
post_response.headers['Access-Control-Allow-Origin'] = '*'
post_response.headers['Access-Control-Allow-Methods'] = 'GET, POST'
return (post_response.status_code)
您通常不想陷入手動處理 CORS 標頭的困境,請嘗試使用中間件,例如https://flask-cors.readthedocs.io/en/latest/#route-specific-cors-via-decorator
但是,特別是圍繞您的響應,您實際上從未返回標頭,只是一個狀態代碼。
如果您在 GCP 上看到示例,您會發現您需要在響應中設置 ACAO = * header。 https://cloud.google.com/functions/docs/writing/http#preflight_request
# Set CORS headers for the main request
headers = {
'Access-Control-Allow-Origin': '*'
}
return ('Hello World!', 200, headers) // Need the Headers in the Response
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.