Reputation: 193
I'm setting up my first application on Google Cloud Run and now want to connect the server with my website. However I've run into CORS issues.
I tried fixing it in my code by using flask_cors. I can see on my requests coming from localhost that they do include the CORS headers, but it doesn't from Cloud Run.
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
I've also tried setting CORS on the buckets it's using behind the scenes. Used the following code
gsutil cors set cors-json-file.json gs://
Link: https://cloud.google.com/storage/docs/configuring-cors
I expected to find instructions on how to set CORS on Cloud Run somewhere, but haven't been able to find any. I tried making my container/API support CORS, but when I push it to Cloud Run it "goes away".
Help would be much appreciated!
Upvotes: 4
Views: 5457
Reputation: 45312
I've edited the Cloud Run python sample like you described
import os
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
@app.route('/')
def hello_world():
return 'Hello, world!\n'
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
I am able to get access-control-allow-origin: *
header both locally and remotely on Cloud Run.
docker run --rm -i -e PORT=8080 -p 8080:8080 gcr.io/ahmetb-samples-playground/run/cors-test
$ curl -v http://localhost:8080
< HTTP/1.1 200 OK
< Server: gunicorn/19.9.0
< Date: Mon, 22 Apr 2019 18:23:06 GMT
< Connection: keep-alive
< Content-Type: text/html; charset=utf-8
< Content-Length: 14
< Access-Control-Allow-Origin: *
Cloud Run:
$ curl -v https://cors-test-dpyb4duzqq-uc.a.run.app
< HTTP/2 200
< content-type: text/html; charset=utf-8
< access-control-allow-origin: *
< x-cloud-trace-context: 8503b029795fdc57bbc4267961806847;o=1
< date: Mon, 22 Apr 2019 18:23:30 GMT
< server: Google Frontend
< content-length: 14
Both responses carry the access-control-allow-origin
header set in your application. Cloud Run doesn't strip off this header.
I'm not sure how/why GCS CORS permissions are relevant to this question. If you want to serve websites directly from GCS Buckets, read Hosting a static Website on GCS.
If you’re just proxying the request from Cloud Run to GCS, yes, it might be inheriting the CORS headers from the GCS response. I recommend you inspect those headers.
Upvotes: 2