使用 pythonflask-restful 和消费 AngularJS 时出现 CORS(跨源...)错误(使用 $http)

2024-03-03

我使用 python 程序通过flask-restful 扩展提供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。 这些是帖子的标题(从 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

我已经尝试过这个

  • Adding @cors.crossdomain(origin='*')在 get 和 post 方法之上(https://github.com/twilio/flask-restful/pull/131 https://github.com/twilio/flask-restful/pull/131)
  • 添加这个api.decorators=[cors.crossdomain(origin='*')]到整个 api (Flask-restful 的 CORS 上的类型错误 https://stackoverflow.com/questions/20147299/typeerror-on-cors-for-flask-restful)
  • 正如您所看到的,我已经点击了此处提供的答案之一的链接(Flask RESTful 与 Angular 的跨域问题:PUT、OPTIONS 方法 https://stackoverflow.com/questions/19962699/flask-restful-cross-domain-issue-with-angular-put-options-methods)但我没有得到实际的答案。我不想重写任何后端,并且 options 方法对我的课程也没有帮助......

您可以使用 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/ http://tutsbucket.com/tutorials/building-a-blog-using-flask-and-angularjs-part-1/

本教程还使用 Flask-restful。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pythonflask-restful 和消费 AngularJS 时出现 CORS(跨源...)错误(使用 $http) 的相关文章

随机推荐