我正在尝试从 ionic 应用程序将数据发送到 Google 云功能,但不断收到以下错误:
从源“http://localhost:8100”访问“https://xxxxxxxxxxxxxxx.cloudfunctions.net/upload_data”处的 XMLHttpRequest 已被 CORS 策略阻止:Access 不允许请求标头字段内容类型-预检响应中的 Control-Allow-Headers。
即使删除请求标头,也会显示相同的错误。 如果有一点帮助,我们将不胜感激,谢谢。
我的打字稿代码:
var httpheader = new HttpHeaders();
httpheader.append('Accept','application/json');
httpheader.append('Content-Type','application/json');
let data = {"testbody":"this is test data"};
await this.http.post('https://xxxxxxxxxxxxxxxx.cloudfunctions.net/upload_data',data
,{headers:httpheader}).subscribe((resp)=>{
console.log(resp);
});
python云函数:
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':
headers={'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'GET',
'Access-Control-Allow-Headrs':'Content-Type',
'Access-Control-Max-Age':'3600'
}
return ('',204,headers)
headers={'Access-Control-Allow-Origin':'*'}
request_json = request.get_json(silent=True)
request_args = request.args
if request_json and 'testbody' in request_json:
testname = request_json['testbody']
elif request_args and 'testbody' in request_args:
testname = request_args['testbody']
else:
testname = 'Nothing sent'
return (jsonify(testname),200,headers) Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
CORS相关配置需要在服务器端代码中完成。从您的问题中,我看到您在Python中使用Flask框架。所以需要在Flask中配置CORS如下:通过运行安装flask-cors -
考虑以下示例端点代码:
from flask import Flask from flask_cors import CORS, cross_origin app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' @app.route("/") @cross_origin() def helloWorld(): return "Hello, cross-origin-world!"更新
在
Production环境中,请禁止禁止使用Access-Control-Allow-Origin':'*'。相反,您应该whitelist您的域名。阅读有关此内容的更多信息此处和此处。此外,如果您将
Ionic 与 Capacitor一起使用,我建议使用 Http 插件。如果可能,您还可以编写自己的自定义插件来使用底层操作系统平台特定的API 实现网络调用natively,因为这可以防止发生任何 CORS 相关问题。参考链接:
Flask CORS 配置
允许 Flask 端点使用 CORS