【问题标题】:Flask request.get_json() not receiving anything from $.post() request [duplicate]烧瓶 request.get_json() 没有收到来自 $.post() 请求的任何内容[重复]
【发布时间】:2018-12-03 08:58:10
【问题描述】:

我正在尝试在 JavaScript 和 Python 之间传递数据,并且我正在使用 JSON 变量来做到这一点,但似乎每当我从 JavaScript 发出 POST 请求时,Python 接收器方法中的 request.get_json() 都不会选择当我打印request.get_json() 时,添加任何内容并打印None

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

【问题讨论】:

    标签: javascript python json post flask


    【解决方案1】:

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

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

    或者,您可以尝试使用 get_json(force=True)[2] 强制 Flask 忽略内容类型

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 2019-12-24
      • 2019-10-25
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多