使用python flaskrestful和消费AngularJS(使用$http)时出现获取CORS(CrossOrigin…)错误

2024-06-01 06:18:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个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)

这是我的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

我已经试过了


Tags: nonameselfapirestfulapphttpflask
3条回答

烧瓶延伸烧瓶cors(https://github.com/corydolphin/flask-cors)对我很好。

您可以使用after_请求挂钩解决此问题:

@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。

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

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

def options(self):
    pass

要使整个工作正常,请使用

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

我不知道为什么,但我必须显式地将所有的headers添加到列表中;使用headers = '*'对我不起作用。在将资源连接到API之前,可能还必须添加装饰器。

相关问题 更多 >