我在将数据发送到 Flask 服务器时遇到问题。当我使用 Postman 时,示例数据发布得很好,但我无法从前端执行此操作。
该表单是动态生成的,如下所示:
<div class="container" id="form-wrapper">
<form
id="comment-form"
method="POST"
onsubmit="send_comment(event)"
class="border p-4 mt-4 rounded"
>
<legend class="border-bottom mb-4">Register</legend>
<div class="form-group">
<label for="comment">Comment</label>
<textarea
rows="3"
class="form-control"
id="comment"
aria-describedby="name_help"
name="comment"
></textarea>
<input
type="hidden"
class="form-control"
id="geom"
name="geom"
value="${coords25832[0]} ${coords25832[1]}"
/>
</div>
<div class="form-group">
<button type="submit" class="btn-sm btn-primary">Save</button>
</div>
</form>
</div>
这是发送数据的函数:
function send_data(event) {
event.preventDefault();
let data = new FormData();
data.comment = document.querySelector("form #comment").value;
data.geom = document.querySelector("form #geom").value;
}
// Example data
// data = {"comment":"sd","geom":"567398.6224792203 7027428.422090762"}
fetch(`${baseurl}/api/comment`, {
method: "POST",
headers: new Headers({
//'Content-Type': 'application/x-www-form-urlencoded'
"Content-Type": "application/json",
}),
body: data,
})
.then(function (res) {
return res.json();
})
.then(function (data) {
alert(JSON.stringify(data));
})
.catch(function (error) {
console.log("Request failure: ", error);
});
最后是我的路线。我正在尝试获取发布的数据。我已经删除了保存到数据库等的代码,如下。我只是想获取服务器端的数据。但它失败了,我不明白为什么。我只是想发布 JSON 或表单数据,但我无法让它工作,我似乎无法获取发布的数据。不知道是前端问题还是后端问题。
@mod.route('/comment', methods=['POST'])
def map_comment():
if request.method == "POST":
print("I am a post")
if request.form:
print("I have form data")
# print(request.form['kommentar'])
if request.data:
print("I have data")
if request.json:
print("I have json")
# Do stuff with the data...
else:
print("fail")
最佳答案
首先,您的端点缺少返回值:
from flask import jsonify
@mod.route('/comment', methods=['POST'])
def map_comment():
if request.method == "POST":
print("I am a post")
if request.form:
print("I have form data")
#print(request.form['kommentar'])
if request.data:
print("I have data")
if request.json:
print("I have json")
# Do stuff with the data...
return jsonify({"message": "OK"})
else:
print("fail")
return jsonify({})
并且 POST 的数据应格式化为 JSON,以便 Flask 可以成功解析它。
{
method: "POST",
headers: new Headers({
//'Content-Type': 'application/x-www-form-urlencoded'
'Content-Type': 'application/json'
}),
body: JSON.stringify(data)
})
由于 json 格式错误,服务器在访问 request.json
时引发异常。
关于post - 无法使用 fetch api 将表单数据发布到 Flask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58344565/