簡體   English   中英

使用python flask-restful並消耗AngularJS時使用CORS(Cross-Origin ...)錯誤(使用$ http)

[英]Getting CORS (Cross-Origin…) error when using python flask-restful with consuming AngularJS (using $http)

我使用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

我已經試過了

你可以使用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。

如果您使用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之前添加裝飾器。

Flask擴展Flask-cors( https://github.com/corydolphin/flask-cors )對我來說效果很好。

在另一個帖子發布,這是我的解決方案:

要在您的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請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM