简体   繁体   中英

CORS Error in Flask Backend on GCP Cloud Run and Angular

I am developing a dashboard with frontend in Angular, Backend in MySQL and Flask. I had deployed the database on CloudSQL and Flask backend on GCP Cloud Run. During production on my local computer, I faced this error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I fixed it by adding the following code to my flask backend locally:

from flask_cors import CORS
CORS(app, resources={r"*": {"origins": "*"}})

I also tried with the following code before every function on flask and it seemed to work perfectly on local computer:

from flask_cors import cross_origin
@app.route('/api/register_smartbox', methods=['POST'])
@cross_origin()
def register_smartbox():
    recv_req = request.get_json()

The main problem occured when I deployed it on GCP Cloud run. I am using Authenticated invocations over there. Here are the logs that I get on cloud run logs when I send an API request from my browser in Angular app:

Warning 2022-02-24T06:14:41.430198ZOPTIONS4030 B0 msChrome 98 https://<My_URL>.app/api/login_users The request was not authenticated. Either allow unauthenticated invocations or set the proper Authorization header. Read more at https://cloud.google.com/run/docs/securing/authenticating Additional troubleshooting documentation can be found at: https://cloud.google.com/run/docs/troubleshooting#unauthorized-client

And here are the errors I am getting inside the browser

Access to XMLHttpRequest at 'https://<My_URL>.app/api/login_users' from origin 'http://127.0.0.1:5555' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Things that I have tried so far:

  1. Added all of the possible CORS techniques inside Flask
  2. Checked my APIs with POSTMAN and in python requests after deployment on Cloud Run and it seems to work perfectly
  3. Tried building the production build of my angular app to check if there could be a problem on that side. Also included the "credentials" header:
 const headers = {"Content-Type": "application/json", 'Authorization': this.auth_tok, "credentials": 'include'}
  1. Tried the deployed GCP service with CURL and NodeJS. Worked with those as well. So only the problem occurs with browser on Angular app.

I have been stuck on this problem for days. Any sort of help would be much appreciated. Thank you

Authenticated invocations won't work for the CORs requests as your web browser isn't sending the needed auth tokens while it does preflight requests to your service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM