我使用 python 程序来提供带有 Flask-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..")
});
}]);
当我尝试执行 get 或 post 两次时,我得到了这个 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
. 这些是帖子的标题(从萤火虫网络选项卡复制)
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) - 如您所见,我已经关注了此处提供的答案之一的链接(Flask RESTful cross-domain issue with Angular: PUT, OPTIONS methods),但我没有得到实际答案。我不想重写任何后端,options 方法对我的课程也没有帮助......