我试图从离子应用程序发送数据到谷歌云函数,我一直得到以下错误:
CORS策略已阻止从源“http://localhost:8100”访问“https://xxxxxxxxxxxxxx.cloudfunctions.net/upload_data”处的XMLHttpRequest:预检响应中的Access-Control-Allow-Headers不允许请求头字段content-type。
即使当删除请求头显示相同的错误.一点帮助将不胜感激,谢谢.
我的打字脚本代码:
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)
1条答案
按热度按时间vx6bjr1n1#
CORS
的相关配置需要在server side
代码中完成。从您的问题中,我看到您在Python
中使用的是Flask
框架。因此您需要在Flask中配置CORS
如下:运行以下命令安装flask-cors-
考虑以下示例端点代码:
更新
在
Production
环境中,请使用Access-Control-Allow-Origin':'*'
的refrain
。相反,您应该whitelist
您的域。阅读有关here和here的更多信息。另外,如果你使用的是
Ionic with Capacitor
,我建议你使用Http plugin。如果可能的话,你也可以自己编写custom plugin
来使用底层操作系统platform-specific
API实现一个网络调用natively
,因为这将防止任何与CORS相关的问题发生。参考链接:
Flask CORS configuration
Allow CORS for Flask endpoint