You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用XMLHttpRequest向Flask应用发送POST请求时持续出现400错误

XMLHttpRequest向Flask发送POST请求返回400错误的解决方法

问题背景

用XMLHttpRequest向Flask应用发送POST请求时持续收到400错误。此前用jQuery请求遇到CORS问题,改用XMLHttpRequest后CORS问题解决,但出现400错误。原本需求是将表单组装的用户数据发送给Flask应用。

现有代码

Flask应用代码

from flask import Flask, render_template, request, jsonify 
from flask_cors import CORS

app = Flask(__name__) 
CORS(app)

@app.route("/") 
def hello(): 
    return render_template('index.html') 

@app.route('/process', methods=['POST']) 
def process(): 
    data = request.get_json() # 接收JavaScript发送的数据
    print("data")
    # Python处理数据
    result = data['value'] * 2
    return jsonify(result=result) # 返回结果给JavaScript

if __name__ == '__main__': 
    app.run(debug=False) 

JavaScript代码

function submit_clicked() {
    var info = document.getElementsByClassName("info")
    var title = document.getElementById("title").innerText
    console.log(title);
    if (title ==  "Create User Account") {
        const data = {
            "Firstname" : info[0].value,
            "Lastname" : info[1].value,
            "Username" : info[2].value,
            "Email" : info[3].value,
            "Password" : info[4].value,
            "Retype_Password" : info[5].value
        }
        sendData(data)
    }
}
function sendData(data) { 
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "http://127.0.0.1:5000/process"),
    xhr.send(JSON.stringify({ 'value': "value" })),
    xhr.onreadystatechange = function() { 
        if (xhr.readyState === 4 && xhr.status >= 400) { 
          console.log(xhr.response)
        } else { 
          // 请求成功逻辑
        } 
    }
}

错误原因分析

  1. 未设置请求头:XMLHttpRequest发送JSON数据时,没有指定Content-Type: application/json,Flask无法识别请求体格式,request.get_json()会返回None,后续访问data['value']触发错误,返回400状态码。
  2. 未发送目标数据:sendData函数忽略了传入的表单data参数,硬编码发送了无关内容,既不符合需求,也和Flask代码的预期不匹配。
  3. 调试代码无效:print("data")仅打印字符串,无法查看实际接收的数据,不利于排查问题。

修正方案

修正JavaScript代码

添加请求头,发送实际表单数据:

function submit_clicked() {
    var info = document.getElementsByClassName("info")
    var title = document.getElementById("title").innerText
    console.log(title);
    if (title ==  "Create User Account") {
        const data = {
            "Firstname" : info[0].value,
            "Lastname" : info[1].value,
            "Username" : info[2].value,
            "Email" : info[3].value,
            "Password" : info[4].value,
            "Retype_Password" : info[5].value
        }
        sendData(data)
    }
}
function sendData(data) { 
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "http://127.0.0.1:5000/process");
    // 设置请求头,告知服务器请求体为JSON格式
    xhr.setRequestHeader("Content-Type", "application/json");
    // 发送组装好的表单数据
    xhr.send(JSON.stringify(data));
    xhr.onreadystatechange = function() { 
        if (xhr.readyState === 4) {
            if (xhr.status >= 400) { 
                console.log("请求错误:", xhr.response);
            } else { 
                // 处理成功响应
                const responseData = JSON.parse(xhr.response);
                console.log("响应结果:", responseData);
            }
        }
    }
}

修正Flask代码

适配表单数据结构,增加错误处理,修复调试代码:

from flask import Flask, render_template, request, jsonify 
from flask_cors import CORS

app = Flask(__name__) 
CORS(app)

@app.route("/") 
def hello(): 
    return render_template('index.html') 

@app.route('/process', methods=['POST']) 
def process(): 
    data = request.get_json()
    # 处理JSON解析失败的情况
    if not data:
        return jsonify(error="无效的JSON数据"), 400
    # 打印实际接收的数据,便于调试
    print("接收的数据:", data)
    # 根据表单数据处理,示例返回用户基础信息
    full_name = f"{data.get('Firstname', '')} {data.get('Lastname', '')}"
    return jsonify(
        full_name=full_name,
        username=data.get('Username'),
        email=data.get('Email')
    )

if __name__ == '__main__': 
    app.run(debug=False) 

内容的提问来源于stack exchange,提问作者Nun Yabissness

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 05:55:36