簡體   English   中英

將數據和GET請求一起發送到Flask API

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM