Javascript POST 请求 Flask 返回空字典
Javascript POST Request to Flask Returning Empty Dict
在我的代码中,我一直从我的 javascript XML HTTP Post 请求中获取一个空的不可变字典。这里是发送请求的javascript(javascript):
xhr = new XMLHttpRequest();
xhr.open("POST", "https://webpage-hoster--lovethebears1o1.repl.co/save", true)
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
username: infotxt[0],
password: infotxt[1],
number: infotxt[2],
code: input.value,
name: titleBox.value
}));
Python:
@app.route("/save", methods=["POST"])
def save():
try:
print(str(request.form))
username = str(request.form["username"])
pword = str(request.form["password"])
number = int(request.form["number"])
code = str(request.form["code"])
name = str(request.form["name"])
except Exception as e:
print("error-1-" + str(e))
return "error"
return "success"
当我 运行 这个时,我在输出中得到这个:
ImmutableMultiDict([])
error-1-400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
服务器将其视为空字典,即使在发送时其中包含值。
当您将 post 作为 JSON 发送时,它不在 request.form
中。尝试:
from flask import jsonify, request
JSON_received = request.get_json()
print(JSON_received)
print(jsonify(JSON_received)) # note the difference
username = JSON_received["username"]
etc...
在我的代码中,我一直从我的 javascript XML HTTP Post 请求中获取一个空的不可变字典。这里是发送请求的javascript(javascript):
xhr = new XMLHttpRequest();
xhr.open("POST", "https://webpage-hoster--lovethebears1o1.repl.co/save", true)
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
username: infotxt[0],
password: infotxt[1],
number: infotxt[2],
code: input.value,
name: titleBox.value
}));
Python:
@app.route("/save", methods=["POST"])
def save():
try:
print(str(request.form))
username = str(request.form["username"])
pword = str(request.form["password"])
number = int(request.form["number"])
code = str(request.form["code"])
name = str(request.form["name"])
except Exception as e:
print("error-1-" + str(e))
return "error"
return "success"
当我 运行 这个时,我在输出中得到这个:
ImmutableMultiDict([])
error-1-400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
服务器将其视为空字典,即使在发送时其中包含值。
当您将 post 作为 JSON 发送时,它不在 request.form
中。尝试:
from flask import jsonify, request
JSON_received = request.get_json()
print(JSON_received)
print(jsonify(JSON_received)) # note the difference
username = JSON_received["username"]
etc...