How to allow CORS in google cloud run?

蓝咒 提交于 2020-07-23 09:11:31

问题


I have a react microservice (via nginx) deployed onto google cloud run with its environment variable for the backend set to another google cloud run instance that's running gunicorn which is serving the backend.

My Flask app is set up following everything I could find about allowing CORS:

app = Flask(__name__)
app.config.from_object(config)
CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
return app

# Different file, a blueprint's urls:

@blueprint.route('/resources')
@cross_origin()
def get_resources():
...

Yet I'm still getting the dreaded Access to XMLHttpRequest at 'https://backend/resources/' from origin 'https://frontend' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Does anyone have any insight into this/know where else to look in figuring this out? I wanted to set up GKE with my microservices but took the path of least resistance initially to get a POC up in the cloud. I have the backend speaking with my Cloud SQL instance, and I'm so close!!

Thank you


回答1:


You've set up more than you need to. Unless you need to provide different CORS access for different endpoints, the simplest example just requires calling CORS(app):

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/resources")
def get_resources():
  return "Hello, cross-origin-world!"

if __name__ == "__main__":
    app.run('0.0.0.0', 8080, debug=True)

And you'll see that the header is present:

$ curl -I localhost:8080/resources
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 26
Access-Control-Allow-Origin: *
Server: Werkzeug/1.0.1 Python/3.7.4
Date: Tue, 21 Apr 2020 17:19:25 GMT



回答2:


Everything was self inflicted.

As Dustin Ingram mentioned, if you enable CORS for Flask, it will work. I still have NO idea why I was getting the CORS issues at all, I've had CORS enabled for my Flask app from the get go.

After I nuked everything and redeployed, the CORS issues disappeared. However, I still ended up getting either 404s, 405s, and 308s.

There were a couple of issues, all my shortcomings, that in combination gave me those issues. In create-react-app (webpack I think is doing it), environment variables passed into the docker runtime does not get respected, so the environment variable I set in Cloud Run wasn't working at all. Currently I opted for the process.env.VARIABLE || 'hardcoded-url' route. Once I got that figured out, I also remembered trailing slashes in flask URLs are bad.... Those gave me 308s, permanent redirects. Once I got that figured out, I realized during my manual deployments, I wasn't switching the cloud build image to the latest. Sigh. Once I started deploying the latest images, everything started working. Yay!

Thanks Dustin and Gabe for spending your time on my foolishness.




回答3:


I just recently wrestled with this as well... My issue was trying to use some JS library to make my URL requests "easier" and instead was munging the headers on the request side (not the server side). Switched to just using straight XMLHttp and it started working fine. I also switched from application/json to application/x-www-form-urlencoded. I don't know if that made a difference or not, but including it for completeness.

You also shouldn't (I say shouldn't, but you know how that goes) need anything OTHER than:

CORS(app). All the @cross-region stuff, and the config pieces are all only there to make a narrower CORS access so it's not wide open, but you have it wide open anyway in your initial code (CORS(app, resources={r"/*": {"origins": "*"}}) is the same I believe as CORS(app)).

Long story, short, try looking at the request object, rather than the Flask side.

Edit: Adding the request code that worked for me after I couldn't get the "fetch" library working:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", <url>, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhttp.send(Data)


来源:https://stackoverflow.com/questions/61347316/how-to-allow-cors-in-google-cloud-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!