使用 python flask-restful 并使用 AngularJS(使用 $http)时出现 CORS(Cross-Origin...)错误

Dom*_*nik 3 javascript python cors angularjs flask-restful

我使用 python 程序提供带有flask-restful扩展的restful服务。我想用 AngularJS 应用程序使用它。在我的本地主机上一切正常(目前)。为了使用服务,我使用 AngularJS $http,如下所示。每次我打电话时,我都会收到这个该死的 CORS 错误(见下文)...

在搜索了一天半之后,我尝试了很多不同的东西,但没有任何东西可以帮助我防止这个问题,我真的不知道还能做什么.. 不幸的是,flask-restful 站点上没有官方文档。

我不确定我是否遗漏了任何明显的东西,或者这是否真的很难在这种技术组合中工作......

在我的帖子末尾,您会看到我已经尝试过的事情的列表......

curl顺便说一句,一个简单的作品......

我很高兴为您提供任何帮助!

这是相关的python代码:

app = Flask(__name__)
api = Api(app)

class DatabaseRestRoomList(Resource):

def __init__(self):
    self.reqparse = reqparse.RequestParser()
    self.reqparse.add_argument('name', type=str, required=True,
        help='No room name provided')
    super(DatabaseRestRoomList, self).__init__()

def get(self):
    #make some logic to give a dict for the variable roomlist
    return (roomlist)

def post(self):
    args = self.reqparse.parse_args()
    name = args['name']
    db.createRoom(name)
    return ({'success': 'yes'})

api.add_resource(DatabaseRestRoomList, '/room')

if __name__ == '__main__':
    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

这是我的 Angularjs 服务代码:

app.service('deviceService', ['$http',
        function ($http) {

  this.getAllRooms = function () {
    var roomlist;
    var urlbase = "http://localhsot:5000"
    var urltail = "room"
    var newroom = { 'name': "NewXYRoom" };

    $http.post(urlbase + '/' + urltail, newroom).
    success(function (data, status, headers, config) {
        alert("success");
    }).
    error(function (data, status, headers, config) {
        alert("error..")
    });
}]);
Run Code Online (Sandbox Code Playgroud)

当我尝试执行 get 或 post 两次时,我收到此 cors 错误...(当然还有我的错误警报)

XMLHttpRequest cannot load http://localhsot:5000/room. No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://localhost:53144' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)

如果我“只”做一个GET错误发生在 get 本身。如果我这样做,POST我会在OPTIONS. 这些是帖子的标题(从萤火虫网络选项卡复制)

Answer-Header
Cache-Control   no-cache
Connection  Keep-Alive
Content-Length  619
Content-Type    text/html; charset=utf-8
Pragma  no-cache
Proxy-Connection    Keep-Alive

Request-Header
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-us,de-de;q=0.8,de;q=0.5,en;q=0.3
Access-Control-Request-He...    content-type
Access-Control-Request-Me...    POST
Cache-Control   no-cache
Connection  keep-alive
Host    localhsot:5000
Origin  http://localhost:53144
Pragma  no-cache
User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0
Run Code Online (Sandbox Code Playgroud)

我已经试过了

Joh*_*enn 8

您可以使用 after_request 钩子解决这个问题:

@app.after_request
def after_request(响应):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    返回响应

您可以在此处查看有关如何使用它的演示 - http://tutsbucket.com/tutorials/building-a-blog-using-flask-and-angularjs-part-1/

本教程还使用 Flask-restful。