如何將資料從 ionic 應用程式發佈到 Google Cloud Function
P粉439804514
P粉439804514 2024-02-04 09:41:03
0
1
394

我正在嘗試從 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學習者快速成長!