在使用python flask-restful和AngularJS(使用$ http)时出现CORS(Cross-Origin ...)错误 [英] Getting CORS (Cross-Origin...) error when using python flask-restful with consuming AngularJS (using $http)
问题描述
我使用python程序通过flask-restful扩展提供宁静的服务. 我想通过AngularJS应用程序来使用它.一切正常(目前)在我的本地主机上. 为了使用该服务,我使用AngularJS $ http,如下所示. 每次我打电话时,都会收到该死的CORS错误(如下所示)...
I use a python program for providing a restful service with the flask-restful extension. I want to consume it with a AngularJS app. Everything works (for the moment) on my localhost. For consuming the service I use AngularJS $http as you can see below. Everytime I do a call I get this damn CORS error (see below)...
在搜索了一天半后,我尝试了许多不同的方法,但是没有任何方法可以帮助我防止出现此问题,而且我真的不知道该怎么办.
I tried many different things after searching for one and a half day but nothing helps me to prevent this problem and I really don't know what else to do.. Unfortunately there is no official documentation at the flask-restful site.
我不确定是否遗漏了任何明显的东西,或者真的很难在这种技术组合中工作……
I'm not sure if I'm missing anything obvious or if this is really that difficult to get working in this combination of technologies...
在我的帖子末尾,您会看到我已经尝试过的东西的清单...
At the end of my post you see a list of things I already tried...
一个简单的curl
可以正常工作...
A simple curl
works by the way...
我将很高兴提供任何帮助!
I would be glad for any provided help!
这是相关的python代码:
Here is the relevant python code:
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服务代码:
Here is my Angularjs service code:
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..")
});
}]);
当我尝试进行一次get或post两次操作时,都会收到此cors错误...(当然还有我的错误警报)
When I try to do a get or post both times I get this cors error... (and of course my error alert)
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网络标签复制)
If I "only" do a GET
the error occurs on the get itself. If I do the POST
I get the error at OPTIONS
.
These are the headers (coppied from the firebug network tab) in case of the post
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
我已经尝试过了
- 在get和post方法上方添加
@cors.crossdomain(origin='*')
( https://github. com/twilio/flask-restful/pull/131 ) - 将此
api.decorators=[cors.crossdomain(origin='*')]
添加到整个api( CORS上的TypeError导致烧瓶不稳定) - 如您所见,我已经按照此处提供的答案之一进行了链接(
- Adding
@cors.crossdomain(origin='*')
above the get and post methods (https://github.com/twilio/flask-restful/pull/131) - Adding this
api.decorators=[cors.crossdomain(origin='*')]
to the whole api (TypeError on CORS for flask-restful) - As you can see I already followed the links from one of the answers provided here (Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods) but I don't get the actual answer. I don't want to rewrite any backend and the options method didn't help in my classes, too...
推荐答案
您可以使用after_request挂钩解决此问题:
You can solve this using the after_request hook:
@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/
You can see a demo on how to use it here - http://tutsbucket.com/tutorials/building-a-blog-using-flask-and-angularjs-part-1/
本教程还使用了Flask-restful.
The tutorial also uses Flask-restful.
这篇关于在使用python flask-restful和AngularJS(使用$ http)时出现CORS(Cross-Origin ...)错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!