启用CORS Google Cloud FunctionPython

问题描述

可以在Google Cloud Functions中使用您flask_cors吗?

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

flask_cors程序包在本地有效,但在部署到Cloud Functions时无效。

我尝试了许多不同的方法,如GCP建议的https://cloud.google.com/functions/docs/writing/http 但我仍然收到该CORS错误

对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。

解决方法

否,app变量在Cloud Functions中不可用。

相反,您可以手动处理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)

有关更多详细信息,请参见https://cloud.google.com/functions/docs/writing/http#handling_cors_requests

,

@mdev,我遇到了类似的问题,并通过在 cors_enabled_function 的开头添加预检请求的 CORS 标头来解决它(正如 Dustin Ingram 建议的那样);我在函数结束时留下的主要请求的 CORS 标头(这种方式包括返回语句中的响应,无论是 JSON、文本等)。换句话说,我将主函数代码放在预检和主 CORS 请求之间。

,

如果您已经在使用 flask,那么最简单的方法是使用 flask-cors

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

像下面这样装饰你的云功能,你就完成了。

from flask_cors import cross_origin

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

或者您可以根据需要添加尽可能多的功能,如下所示。

from flask_cors import cross_origin

@cross_origin(allowed_methods=['POST'])
@json
def fun_function(request):
    # enter code here
,

云函数中没有 APP。您可以按照 google cloud documentations 中的说明设置 CORS 标头,并按照您在 Flask 中的编写方式返回您的 JSON。

下面的示例名为 hello_world,用于发布请求。它返回 CORS 的状态和标题。

from flask import jsonify

def hello_world(request):
    request_json = request.get_json()
    # 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': 'POST',headers)

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

   if request_json and 'labels' in request_json:
        # THIS IS THE PLACE YOU WRITE YOUR CODE.
        # AWLAYS RETURN WITH THE HEADERS AND STATUS
        return (jsonify({"ok": "Great Day 2"}),headers)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...