我试图将我在Python-Flask中开发的API与AngularJS API结合使用:
运行这个服务器(python file.py服务器将提供服务,Python file.py post将在服务中使用json)我得到了一切正常工作,我能够发送数据并将其接收回来。
from flask import Flask, request, jsonify, send_from_directory
from json import dumps, loads
app = Flask(__name__, static_folder=".", template_folder=".")
@app.after_request
def add_headers(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization, data')
return response
@app.route("/")
def main():
content = loads(request.data)
return jsonify({"status":"ok", 'content':content})
@app.route("/index.html")
def index():
return send_from_directory(".", "index.html")
if __name__ == '__main__':
import sys
if sys.argv[1] == "serve":
app.run(host="0.0.0.0", debug=True, port=9999)
elif sys.argv[1] == "post":
import requests
ans = requests.get("http://localhost:9999/", data=dumps({"what":"is going on?"}))
print ans.text
但是当我使用这个简单的Angular应用程序时,服务器崩溃,因为request.data不是有效的JSON,我试图将信息作为URL参数发送,并且在HTTP数据头中,也没有成功。
</head>
<body>
</body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{myWelcome}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope, $http) {
var json = {
what: JSON.stringify(" is going on?")
};
try {
$req = $http({
method: 'get',
url: "http://localhost:9999",
data: JSON.stringify(json),
//Data: JSON.stringify(json),
headers: {
'Content-Type': 'application/'
}
}).success(function (data) {
console.log('Received data via HTTP from ', [data]);
}).error(function (data, status) {
console.log("Error receiving from HTTP");
});
} catch (err) {
console.log( null, "EXCEPTION: " + err.message);
}
</script>
</html>
有关如何执行此操作的任何示例?
答案 0 :(得分:0)
如果确实希望通过GET请求传递数据,您可以通过请求参数来完成:
JS:
$req = $http({
method: 'get',
url: "http://localhost:9999",
params: {data: your_json_as_string}
})
烧瓶中:
@app.route("/")
def main():
content = loads(request.args['data'])
return jsonify({"status":"ok", 'content':content})