Skip to main content
 首页 » 编程设计

python之Flask-RESTplus CORS 请求不在响应中添加 header

2024年09月07日14dyllove98

我在尝试为我的 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 

如果我编写了一个小的 javascript 片段并尝试在浏览器中启动它,我会收到错误消息,因为没有 CORS header 。我看到 Flask-Restplus 已经在处理 OPTIONS 请求,而我没有告诉他任何事情。 (根据 this link ,这是有道理的,提到自 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]: 
        ... 

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

我错过了什么吗?

请您参考如下方法:

使用 Flask-CORS , 它有效:

from flask import Flask, request 
from flask_restplus import Resource, Api, fields 
from flask_cors import CORS 
 
# configuration 
DEBUG = True 
 
# instantiate the app 
app = Flask(__name__) 
api = Api(app) 
app.config.from_object(__name__) 
 
# enable CORS 
CORS(app, resources={r'/*': {'origins': '*'}})