私は、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
私はすでにこれを試しました
@cors.crossdomain(origin='*')
get メソッドと post メソッドの上に追加します ( https://github.com/twilio/flask-restful/pull/131 )api.decorators=[cors.crossdomain(origin='*')]
これをAPI全体に追加します(フラスコレストフルのCORSの TypeError)- ご覧のとおり、ここで提供されている回答の 1 つからのリンクを既にたどっています ( Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods ) が、実際の回答は得られません。バックエンドを書き直したくないし、私のクラスでも options メソッドは役に立ちませんでした...