3

私は、flask-restful 拡張で安らかなサービスを提供するために Python プログラムを使用しています。AngularJS アプリで使用したい。すべてが私のローカルホストで(今のところ)動作します。サービスを利用するために、以下に示すように AngularJS $http を使用します。電話をかけるたびに、このひどいCORSエラーが発生します(以下を参照)...

1日半検索した後、さまざまなことを試しましたが、この問題を防ぐのに役立つものは何もなく、他に何をすべきか本当にわかりません..残念ながら、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

私はすでにこれを試しました

4

4 に答える 4

3

CORS を使用して AngularJS 呼び出しを行うと、すべてのデータを送信する前POSTに、(MIME/Content-Type に応じて)OPTIONSクロスサーバー リクエストが有効であることを確認する前の呼び出しがトリガーされることがあります。POSTAPI にはメソッドがないためoptions、Flask は Flask-Restful の代わりに呼び出しを受け取り、API リソースに対してのみ定義されている CORS オプションを設定しません。

ダミーoptionsハンドラーを定義することで問題を解決できます。

def options(self):
    pass

全体を機能させるには、次を使用してcorsオプションを定義します

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

理由はわかりませんがheaders、リストにすべてを明示的に追加する必要がありました。を使用してheaders = '*'もうまくいきませんでした。リソースを API に接続する前に、デコレータを追加する必要がある場合もあります。

于 2014-05-29T17:38:06.180 に答える