Flask-RESTplus CORS 请求未在响应中添加标头

ElC*_*ine 6 python rest flask

我在尝试为我的 REST API 设置 CORS 时遇到问题。我目前正在使用Flask-Restplus包。这是我的端点的样子:

@api_ns.route('/some/endpoint')
@api_ns.response(code=400, description='Bad Request.')
class AEndpointResource(Resource):

    @api_ns.param(**api_req_fields.POST_DOC)
    @api_ns.expect(POST_REQUIRED_BODY)
    @api_ns.marshal_with(code=201,
                     fields=my_api_models.MyEndpointResponse.get_serializer(),
                     description=my_api_models.MyEndpointResponse.description)
    def post(self) -> Tuple[my_api_models.MyEndpointResponse, int]:
        """
        The post body
        """
        # Some logic here
        return response, 200
Run Code Online (Sandbox Code Playgroud)

如果我编写一个小的 javascript 片段并尝试在浏览器中启动它,我会收到错误消息,因为没有 CORS 标头。我看到 Flask-Restplus 已经在处理 OPTIONS 请求,而我没有告诉他任何事情。(根据此链接,这是有道理的,提到自 Flask 0.6 以来, OPTIONS 请求是自动处理的)

我的问题是,即使我尝试使用以下方法装饰我的端点:

from flask-restplus import cors   # <--- Adding this import

...
class AnEndpointResource(Resource):
    ...
    @my_other_decorators
    ...
    @cors.crossdomain(origin='*')  # <--- Adding this new decorator on my endpoint
    def post(self) -> Tuple[my_api_models.MyEndpointResponse, int]:
        ...
Run Code Online (Sandbox Code Playgroud)

没有任何变化,我仍然得到与以前相同的结果。我从像以前一样自动处理的 OPTIONS 请求中获得 HTTP 200,但在响应中没有看到我的新标头(即 Access-Control-Allow-Origin)。

我错过了什么吗?

小智 0

我进行了测试,您正在查找的标头已添加到对后续请求的响应中GET。装饰器有一个默认设置的@cors.crossdomain选项。这意味着您的 OPTIONS 请求仍将被自动处理。automatic_optionsTrue

请参阅测试来检查它应该如何工作。

flask_restplus.cors模块没有记录,因此不确定是否应该使用它。