如何将数据从 ionic 应用程序发布到 Google Cloud Function
P粉439804514
P粉439804514 2024-02-04 09:41:03
0
1
391

我正在尝试从 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)

P粉439804514
P粉439804514

全部回复(1)
P粉763662390

CORS相关配置需要在服务器端代码中完成。从您的问题中,我看到您在 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':'*'。相反,您应该 whitelist 您的域名。阅读有关此内容的更多信息此处此处

此外,如果您将 Ionic 与 Capacitor 一起使用,我建议使用 Http 插件。如果可能,您还可以编写自己的 自定义插件 来使用底层操作系统 平台特定的 API 实现网络调用 natively ,因为这可以防止发生任何 CORS 相关问题。

参考链接:

Flask CORS 配置

允许 Flask 端点使用 CORS

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!