
flask 接收 xmlhttprequest 的 post 请求时返回 400 错误,通常因请求体格式不匹配 `request.form` 解析要求所致;本文详解如何通过 `formdata` 正确构造请求,并修正后端数据解析逻辑。
在 Flask 中,request.form 仅能解析 application/x-www-form-urlencoded 或 multipart/form-data 类型的请求体。而原始 JavaScript 代码中使用 xmlhttp.send("json=" + encodeURI(...)) 发送的是纯文本(text/plain)请求体,Flask 无法将其自动解析为 form 字典,因此访问 request.form["json"] 会触发 400 Bad Request —— 这是 Flask 的默认安全行为,防止无效或恶意表单提交。
✅ 正确做法是使用 FormData 对象封装数据,它会自动设置合适的 Content-Type(如 multipart/form-data; boundary=...),并确保数据被 Flask 正确识别为表单字段:
function del(e) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function () {
if (this.status !== 200) return;
try {
const json = JSON.parse(this.responseText);
const newJson = json.filter(item => item.name !== e.parentElement.childNodes[2].textContent);
const postReq = new XMLHttpRequest();
postReq.open("POST", "/orders");
const formData = new FormData(); // ✅ 创建 FormData 实例
formData.append("json", JSON.stringify(newJson)); // ✅ 自动编码,无需手动 encodeURI
postReq.send(formData); // ✅ 自动设置 Content-Type 并发送
} catch (err) {
console.error("JSON 处理失败:", err);
}
};
xmlhttp.open("GET", "/json");
xmlhttp.send();
}⚠️ 同时,后端 Flask 路由也需优化以增强健壮性:
- 避免直接访问 request.form["json"](可能 KeyError);
- 区分 GET/POST 逻辑,避免在 GET 分支中误执行 POST 相关操作;
- 使用 request.form.get() 安全取值,并校验数据有效性;
- 移除全局变量 global orders(非线程安全,不推荐用于生产);
- 返回明确响应(如 return "OK" 或 jsonify({"status": "success"})),便于前端调试。
优化后的 Flask 路由示例:
from flask import Flask, request, render_template, jsonify
import json
from urllib.parse import unquote
@app.route("/orders", methods=["POST", "GET"])
def order():
global orders # ⚠️ 仅用于演示;生产环境请改用数据库或线程安全缓存
if request.method == "GET":
return render_template("orders.html", orders=orders)
elif request.method == "POST":
# 安全获取 form 数据
json_str = request.form.get("json")
if not json_str:
return "Missing 'json' field", 400
try:
parsed_data = json.loads(json_str) # ✅ 直接解析 JSON 字符串
orders = parsed_data
return jsonify({"status": "success", "count": len(orders)})
except (json.JSONDecodeError, TypeError) as e:
return f"Invalid JSON: {e}", 400? 关键总结:
- 前端必须用 FormData(而非字符串拼接)发送表单数据,才能被 request.form 正确读取;
- 后端应始终校验 request.form.get() 返回值,并捕获 JSON 解析异常;
- 避免在 GET 和 POST 共享逻辑中重复访问 request.form,防止 400 错误扩散;
- 开发阶段可启用 Flask 调试模式(app.run(debug=True))查看详细错误日志,快速定位问题根源。










