Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enabling CORS Google Cloud Function (Python)

Can use you flask_cors in Google Cloud Functions?

app = Flask(__name__)
cors = CORS(app)

Locally this flask_cors package works but when deployed onto Cloud Functions it does not.

I have tried many different ways, as GCP has suggested https://cloud.google.com/functions/docs/writing/http but I am still getting that CORS error:

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

like image 865
mdev Avatar asked Sep 25 '20 20:09

mdev


2 Answers

No, the app variable is not available in Cloud Functions.

Instead you can manually handle CORS:

def cors_enabled_function(request):
    # For more information about CORS and CORS preflight requests, see
    # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
    # for more information.

    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*'
    }

    return ('Hello World!', 200, headers)

See https://cloud.google.com/functions/docs/writing/http#handling_cors_requests for more details.

like image 199
Dustin Ingram Avatar answered Sep 17 '22 20:09

Dustin Ingram


If you're using flask already then the easiest way is to use flask-cors

https://github.com/corydolphin/flask-cors

Decorate your cloud function like below and you're done.

from flask_cors import cross_origin

@cross_origin()
@json
def fun_function(request):
    # enter code here

Or you can add as much functionality as you need as shown below.

from flask_cors import cross_origin

@cross_origin(allowed_methods=['POST'])
@json
def fun_function(request):
    # enter code here
like image 32
SARose Avatar answered Sep 17 '22 20:09

SARose