【发布时间】:2018-11-15 10:56:35
【问题描述】:
我在尝试为我的 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 sn-p 代码并尝试在浏览器中启动它,我会收到错误消息,因为没有 CORS 标头。我看到 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,但在响应中没有看到我的新标头(即 Access-Control-Allow-Origin)。
我错过了什么吗?
【问题讨论】: