Use Jquery ajax exchange data with back-end Flask

A recent project encountered a pit, jquery ajax data to the flask using a transfer when using the back end anyway request.data not obtain the data, the code is as follows:

front end:

<script>
      function checkUser() {
          var usercookie = $.cookie("validate");
          $.ajax({
                url: "http://127.0.0.1:5000/checkCookie",
                type: "POST",
                data: {'cookie': '123123'},
                success: function(data){
                    console.log(data);
                },
                error: function(err) {
                    the console.log ( " authentication failure " );
                }
            });
      }
</script>

Whether provided contentType file application / JSON; charset = UTF-. 8 ' , or JSON, is able to get back end test data in the following code:

@app.route('/checkCookie', methods=['POST'])
def checkCookie():
    data = request.data
    if data :
        return "success", 200
    else:
        return "error", 400

However, if request.data to request.get_data (), will be available directly to the GET byte parameters: b'cookie = 123123 ', when a plurality of parameters passed, becomes a = 123 & b = 234 this form, it is certainly not what we want to deal with them will be very troublesome. So get into the last half of the form, the form can be sent directly to json, so it is a lot easier back-end processing:

front end:

<script>
      function checkUser() {
          var usercookie = $.cookie("validate");
          Udata = JSON.stringify({"Uid": usercookie});
          $.ajax({
                url: "http://127.0.0.1:5000/checkCookie",
                type: "POST",
                contentType: 'application/json; charset=UTF-8',
        data: Udata,
                success: function(data){
                    console.log(data);
                },
                error: function(err) {
                    the console.log ( " authentication failure " );
                }
            });
      }
</script>

rear end:

@app.route('/checkCookie', methods=['POST'])
def checkCookie():
    data = request.get_json()
    if data:
        return "success", 200
    else:
        return "error", 400

After this change, direct access to the rear end of the front end json data transmitted, and the method can be directly obtained by the data format json get_json ().

 

Guess you like

Origin www.cnblogs.com/soledadcat/p/12014402.html