我正在尝试将数据从Flask发送到AngularJS。
@app.route("/data")
def getDataFromDB():
cur.execute("select * from employee")
rows = cur.fetchall()
columns = [desc[0] for desc in cur.description]
result = []
for row in rows:
row = dict(zip(columns, row))
json_row=json.dumps(row)
result.append(json_row)
json_response=json.dumps(result)
response=Response(json_response,content_type='application/json; charset=utf-8')
response.headers.add('content-length',len(json_response))
response.status_code=200
return response
var app=angular.module('myApp',[]);
app.controller("MainController", function($scope,$http){
var done=function(resp){
$scope.lists=resp.data;
};
var fail=function(err){
};
$http.get('http://10.62.XX.XX:8083/data')
.then(done,fail);
});
<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"
type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src="maincontroller.js" type="text/javascript"></script>
</head>
<body ng-app="myApp">
<div id='content' ng-controller='MainController'>
<div>
<ul>
<li ng-repeat='ele in list'>{{ele}}</li>
</ul>
</div>
</div>
</body>
</html>
现在,当我使用jsbin.com访问上面的代码时,我可以看到我的api被调用但在jsbin的输出屏幕上看不到任何内容。这是空白的。 但是当我在eclipse中使用相同的代码时,我发现没有api调用发生。我是否需要做更多工作才能使angularJS工作?我只需用网络浏览器打开index.html。
答案 0 :(得分:2)
如果IP不是您的本地计算机,则需要在服务器上设置CORS。我不熟悉Flask,但看起来有一个package可以解决这个问题。我还找到了sets up CORS for Flask。
的函数from datetime import timedelta
from flask import Flask, make_response, request, current_app
from functools import update_wrapper
def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
@app.route('/')
@crossdomain(origin='*')
def landing():
return jsonify(i_am_a='cross domain resource!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)