How to get POSTed JSON in Flask?

前端 未结 10 1143
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 06:35

I\'m trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the POST with the Postman Chrome extension, and the JSON I POST is simply <

10条回答
  •  不知归路
    2020-11-21 06:55

    For all those whose issue was from the ajax call, here is a full example :

    Ajax call : the key here is to use a dict and then JSON.stringify

        var dict = {username : "username" , password:"password"};
    
        $.ajax({
            type: "POST", 
            url: "http://127.0.0.1:5000/", //localhost Flask
            data : JSON.stringify(dict),
            contentType: "application/json",
        });
    

    And on server side :

    from flask import Flask
    from flask import request
    import json
    
    app = Flask(__name__)
    
    @app.route("/",  methods = ['POST'])
    def hello():
        print(request.get_json())
        return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 
    
    if __name__ == "__main__":
        app.run()
    

提交回复
热议问题