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

问题描述 投票:3回答:4

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

在搜索了一天半之后,我尝试了很多不同的东西,但没有什么可以帮助我防止这个问题而且我真的不知道还能做什么......不幸的是,在烧瓶安静的网站上没有官方文档。

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

在我的帖子的最后,你看到我已经尝试过的一系列事情......

一个简单的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)

这是我的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..")
    });
}]);

当我尝试两次获取或发布时,我得到这个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.

如果我“只”做一个GET,则会在get本身上发生错误。如果我做POST我在OPTIONS得到错误。在帖子的情况下,这些是标题(从firebug网络选项卡中删除)

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

我已经试过了

javascript python angularjs cors flask-restful
4个回答
3
投票

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

@app.after_request
def after_request(response):
    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')
    return response

您可以在这里看到如何使用它的演示 - http://tutsbucket.com/tutorials/building-a-blog-using-flask-and-angularjs-part-1/

本教程还使用了Flask-restful。


2
投票

如果您使用CORS进行AngularJS POST调用,有时它会触发(取决于您的MIME / Content-Type)先前的OPTIONS调用,以在发送所有POST数据之前检查跨服务器请求是否有效。由于您的API没有options方法,Flask接受调用而不是Flask-Restful,并且它不会设置仅为API资源定义的CORS选项。

您可以解决定义虚拟options处理程序的问题:

def options(self):
    pass

要使整个工作正常,请使用以下方法定义cors选项

api.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])] 

我不知道为什么,但我必须明确地将所有headers添加到列表中;使用headers = '*'不适合我。您可能还需要在将资源连接到API之前添加装饰器。


1
投票

Flask扩展Flask-cors(https://github.com/corydolphin/flask-cors)对我来说效果很好。


0
投票

发布on another thread,这是我的解决方案:

要在您的Web服务api上允许远程CORS请求,您可以简单地初始化您的烧瓶restful API,如下所示:

from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"*": {"origins": "*"}})
api = Api(app)

这会将CORS头添加到您的api实例,并允许来自每个源的每个路径上的CORS请求。

© www.soinside.com 2019 - 2024. All rights reserved.