Ionic 如何将数据从离子应用程序发布到Google Cloud Function

rt4zxlrg  于 2023-04-18  发布在  Ionic
关注(0)|答案(1)|浏览(141)

我试图从离子应用程序发送数据到谷歌云函数,我一直得到以下错误:
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)
vx6bjr1n

vx6bjr1n1#

CORS的相关配置需要在server side代码中完成。从您的问题中,我看到您在Python中使用的是Flask框架。因此您需要在Flask中配置CORS如下:
运行以下命令安装flask-cors-

pip install -U 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':'*'refrain。相反,您应该whitelist您的域。阅读有关herehere的更多信息。
另外,如果你使用的是Ionic with Capacitor,我建议你使用Http plugin。如果可能的话,你也可以自己编写custom plugin来使用底层操作系统platform-specific API实现一个网络调用natively,因为这将防止任何与CORS相关的问题发生。
参考链接:
Flask CORS configuration
Allow CORS for Flask endpoint

相关问题