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)
CORS
Relevant configuration needs to be completed in theserver-side
code. From your question, I see that you are using theFlask
framework inPython
. Therefore,CORS
needs to be configured in Flask as follows:Install by running flask-cors -
Consider the following example endpoint code:
renew
In a
Production
environment, please prohibitprohibit
from usingAccess-Control-Allow-Origin':'*'
. Instead, you shouldwhitelist
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 owncustom plug-in
to implementnetwork
calls natively using the underlying operating systemplatform-specific
API implementation, Because this prevents any CORS related issues from occurring.Reference link:
Flask CORS Configuration
Allow Flask endpoints to use CORS