How to post data from ionic app to Google Cloud Function
P粉439804514
P粉439804514 2024-02-04 09:41:03
0
1
447

I'm trying to send data to Google Cloud Functions from an ionic app but I keep getting the following error:

Accessing XMLHttpRequest at 'https://xxxxxxxxxxxxxxx.cloudfunctions.net/upload_data' from origin 'http://localhost:8100' has been blocked by CORS policy: Access disallows request header field content-type - preflight response Control-Allow-Headers in.

The same error is shown even if the request header is removed. Any help would be greatly appreciated, thank you.

My typescript code:

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 cloud function:

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

reply all(1)
P粉763662390

CORSRelevant configuration needs to be completed in the server-side code. From your question, I see that you are using the Flask framework in Python. Therefore, CORS needs to be configured in Flask as follows:

Install by running flask-cors -

pip install -U flask-cors

Consider the following example endpoint code:

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!"

renew

In a Production environment, please prohibit prohibit from using Access-Control-Allow-Origin':'*'. Instead, you should whitelist your domain name. Read more about this here and here.

Also, if you are using Ionic with Capacitor, I recommend using the Http plugin. If possible, you can also write your own custom plug-in to implement network calls natively using the underlying operating system platform-specific API implementation, Because this prevents any CORS related issues from occurring.

Reference link:

Flask CORS Configuration

Allow Flask endpoints to use CORS

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template