烧瓶request.get_json()没有从$ .post()请求中接收任何信息

时间:2018-06-24 17:33:23

标签: javascript python json post flask

我正在尝试在JavaScript和Python之间通信数据,并且正在使用JSON变量进行通信,但是似乎每当我从JavaScript发出POST请求时,Python接收器中的request.get_json()方法是不拾取任何东西,并且在打印None时打印request.get_json()

Python方法可以在将返回的内容返回给JS的情况下使用,但始终为None。我在$.post()方法中做错什么了吗?

JavaScript $.post()调用:

var items = {"robotCoor": {"robot_x": 1, "robot_y": 1},
         "gridParams": {"goal_y": 0, "size_x": 16, "size_y": 16, "goal_x": 0},
         "obsParams": {"obs_x3": 0, "obs_x4": 0, "obs_y4": 0, "obs_x2": 0, "obs_x1": 0, "obs_y1": 0, "obs_y2": 0, "obs_y3": 0},
         "aiParams": {"layers": 0, "learning_rate": 0, "speed": 0}
     };
var stuff = JSON.stringify(items);
console.log(stuff); #prints the correct thing
$.post("receiver", stuff, function( data ) {
    console.log(stuff); #prints the correct thing
    alert("Data: " + data); #alerts with "Data: None"
});

Python接收器方法:

@app.route("/receiver", methods = ["POST"])
def receiver():
    if request.method == "POST":
        stuff = request.get_json()
        print(stuff) #prints None
        stuff = str(stuff)
        print(stuff) #prints None

        return stuff

1 个答案:

答案 0 :(得分:0)

在JavaScript中,将请求的内容类型设置为application/json。否则get_json将始终返回None。一种方法是执行以下操作[1]

$.ajaxSetup({
  contentType: "application/json; charset=utf-8"
});

或者,您可以尝试通过使用get_json(force=True) [2]

来强制Flask忽略内容类型。