我有一个配置了一些CORS选项的Flask-Restful API:
api = Api() api.decorators=[cors.crossdomain(origin='*',headers=['accept','Content-Type'])] ... api.init_app(app)
我的API接受POST请求,如果请求中的数据无效,则可能会失败:
class myAPI(Resource): def post(self): args = request.get_json() if args.get('something'): return {'message': 'Request worked,data received!','something': args['something']} else: abort(500,"Error: Data must contain a 'something' field!")
当我对我的API发出成功的POST请求时,我可以看到CORS选项已正确设置:
... * upload completely sent off: 81 out of 81 bytes * HTTP 1.0,assume close after body < HTTP/1.0 200 OK < Content-Type: application/json < Content-Length: 205 < Access-Control-Allow-Origin: * < Access-Control-Allow-Methods: HEAD,GET,POST,OPTIONS < Access-Control-Max-Age: 21600 < Access-Control-Allow-Headers: ACCEPT,CONTENT-TYPE < Server: Werkzeug/0.9.4 Python/2.7.6
但是,如果我的类中的post调用通过abort方法退出(通过故意将错误数据发送到请求),则响应中缺少Access-Control- *字段:
* upload completely sent off: 75 out of 75 bytes * HTTP 1.0,assume close after body < HTTP/1.0 500 INTERNAL SERVER ERROR < Content-Type: application/json < Content-Length: 51 < Server: Werkzeug/0.9.4 Python/2.7.6