Javascript Flask request.get_json()未从$.post()请求接收任何内容
我试图在JavaScript和Python之间进行数据通信,我使用JSON变量来实现这一点,但似乎每当我从JavaScript发出Javascript Flask request.get_json()未从$.post()请求接收任何内容,javascript,python,json,post,flask,Javascript,Python,Json,Post,Flask,我试图在JavaScript和Python之间进行数据通信,我使用JSON变量来实现这一点,但似乎每当我从JavaScript发出POST请求时,request.Python receiver方法中的get_JSON()在我打印request.get_JSON()时不会拾取任何内容并打印None Python方法将返回一些东西给JS,但它总是None。我的$.post()方法是否出错 JavaScript$.post()调用: var items = {"robotCoor": {"robot_
POST
请求时,request.Python receiver方法中的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中,将请求的内容类型设置为
application/json
。否则get_json
将始终返回None
。一种方法是执行以下操作
或者,您可以尝试使用
get_json(force=True)
强制Flask忽略内容类型。在JavaScript中,将请求的内容类型设置为application/json
。否则get_json
将始终返回None
。一种方法是执行以下操作
或者,您可以尝试使用get\u json(force=True)
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});