[英]Send data together with GET request to flask API
我正在尝试将我在Python-Flask中开发的API与AngularJS API结合使用:
运行此服务器(服务将运行python file.py服务,服务中将提供python file.py发布服务中的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 Data标头中,也没有成功。
</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>
有关如何执行此操作的任何示例?
如果您确实想通过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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.