【发布时间】:2020-07-24 21:07:24
【问题描述】:
我正在尝试按照官方documentation 向 HTTP Cloud Functions 发送授权的 Firebase 请求。
但是,我不断收到错误消息:
从源访问“[CLOUD-FUNCTION-SOURCE-URL]”处的 XMLHttpRequest 'http://127.0.0.1:8080' 已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
我尝试了以下方法:
def cors_enabled_function_auth(request):
# For more information about CORS and CORS preflight requests, see
# https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
# for more information.
# Set CORS headers for preflight requests
if request.method == 'OPTIONS':
# Allows POST requests from origin * Authorization header
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': ['Authorization', 'Content-Type'] ,
'Access-Control-Max-Age': '3600',
'Access-Control-Allow-Credentials': 'true'
}
return ('', 204, headers)
# Set CORS headers for main requests
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
}
print('core logic here')
return ('Hello World!', 200, headers)
在前面(使用 AngularJS)我提出如下请求:
self.getDownloadUrl = function(gcs_reference) {
var url = '[CLOUD-FUNCTION-URL]';
var params = {'param1': 'hello'};
var headers = {
'Content-Type': 'application/json'
}
return firebase.auth().onAuthStateChanged().then(
function (user) {
headers['Authorization'] = user['refreshToken']
return postRequestHTTP(params, url, headers)
},
function (error) {
console.log('error', error)
return error;
}
)
};
function postRequestHTTP(params, url, headers) {
// Generic HTTP post request to an url with parameters
var q = $q.defer();
var body = params;
var req = {
headers: headers
};
$http.post(url, body, req).then(
function(response) {
q.resolve(response)
}, function(error) {
q.reject(error)
}
);
return q.promise;
}
有谁知道这个异端的原因是什么?
【问题讨论】:
标签: javascript python firebase google-cloud-platform google-cloud-functions