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

使用Flask+SQLAlchemy后端POST请求时出现Ajax 400错误求助

Hey Benny, let's break down why you're getting that 400 Bad Request error when sending your POST request to Flask. Here are the most common fixes and checks to run through:

1. Fix CSRF Token Issues (Most Likely Culprit)

If your Flask app uses Flask-WTF (which enables CSRF protection by default), your POST request will fail with a 400 unless you include the CSRF token in the request headers.

First, add this meta tag to your HTML template (so jQuery can grab it):

<meta name="csrf-token" content="{{ csrf_token() }}">

Then update your jQuery AJAX call to include the token in the headers:

$.ajax({
    url: "/create",
    type: "POST",
    // Add this line to send the CSRF token
    headers: { 'X-CSRFToken': $('meta[name="csrf-token"]').attr('content') },
    data: {
        question: question,
        answer1: answer1,
        answer2: answer2,
        answer3: answer3,
        answer4: answer4,
        answer5: answer5,
        answer6: answer6,
        congress: congress,
        session: session,
        date: date,
        lecture: lecture,
        correct: correct
    },
    success: function(){
        console.log("sent");
    },
    error: function(xhr, textStatus, error){
        // Log the actual error response from Flask to debug easier
        console.error("Request failed:", textStatus, error);
        console.log("Flask error details:", xhr.responseText);
    }
});

2. Verify Data Matching Between Frontend and Backend

  • Double-check that every field name in your data object exactly matches what your Flask route expects. For example, if your backend uses request.form.get("question"), make sure you're sending a field named question (no typos like queston).
  • If your Flask route is expecting JSON data instead of form data, adjust your AJAX call:
    $.ajax({
        url: "/create",
        type: "POST",
        headers: { 'X-CSRFToken': $('meta[name="csrf-token"]').attr('content') },
        contentType: "application/json", // Tell Flask you're sending JSON
        data: JSON.stringify({
            question: question,
            answer1: answer1,
            // ... rest of your fields
        }),
        success: function(){ console.log("sent"); },
        error: function(xhr){ console.log(xhr.responseText); }
    });
    
    And in your Flask route, use request.get_json() to parse the data instead of request.form.

3. Check Flask's Console Logs

Flask will almost always print the exact reason for a 400 error in the terminal where you're running the app. Look for lines like:

  • BadRequestKeyError: 'question' (means you're missing that field)
  • CSRF token missing (confirms the token issue)
  • Invalid date format (if your date field is in a format Flask can't parse)

4. Validate Data Types

Make sure the data you're sending matches what your SQLAlchemy model expects:

  • If correct is a boolean field in your model, ensure you're sending a boolean (true/false) instead of a string ("true"/"false").
  • For date, send it in a format Flask can parse (like YYYY-MM-DD) so SQLAlchemy can convert it to a datetime object.

Once you try these steps, the error should be clear. The xhr.responseText in your error callback will also give you direct feedback from Flask, which is super helpful for debugging.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:54:51