我正在尝试使用 Jquery 请求调用我的 Google Cloud Function。由于 CORS 政策,这被浏览器阻止。为了克服这个问题,我尝试了 Google Cloud 函数文档中描述的内容:https://cloud.google.com/functions/docs/writing/http#handling_cors_requests。它说可以使用预检请求启用 CORS。
准确地说,这些是我的 Cloud 函数的第一行:
def hello_world(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
"""
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': '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': '*'
}
我从本地客户端 http://127.0.0.1:5000 调用云函数。
这是我尝试调用 API 的方式,首先执行预检请求,然后执行实际的 API 调用:
$(function () {
console.log("starting preflight");
$.ajax({
url: "https://cloudfunction/recommend",
type: "OPTIONS"
}).always(function () {
console.log("preflight done");
$.post("https://cloudfunction/recommend", {
"some": "data"
}).done(function (data) {
alert("Data Loaded: " + data);
});
});
});
预检请求似乎进行得很顺利,但 Chrome 在实际 API(发布)调用中返回此错误:“从源‘http://127.0.0.1’访问‘https://cloudfunction/recommend’处的 XMLHttpRequest: 5000' 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。”
我已经尝试设置 'Access-Control-Allow-Origin': '*'
和 'Access-Control-Allow-Methods': '*'
以及组合,但都导致了与上述相同的错误。
有人知道这里出了什么问题吗?