简体   繁体   中英

Send data together with GET request to flask API

I'm trying to couple an API I've developed in Python-Flask with an AngularJS API:

Running this server (python file.py serve will serve, and Python file.py post will a json in the service) I get everything working, I'm able to send data and receive it back.

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

But when I use this simple Angular application, the server crashes because there the request.data is not a valid JSON, I've tried to send the info as URL parameter and in the HTTP Data header, no success either.

</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>

Any example on how to do this?

If you really want to pass data with GET request, you can do it through request params:

js:

$req = $http({
            method: 'get',
            url: "http://localhost:9999",
            params: {data: your_json_as_string}
})

flask:

@app.route("/")
def main():
    content = loads(request.args['data'])
    return jsonify({"status":"ok", 'content':content})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM