使用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
dataobject exactly matches what your Flask route expects. For example, if your backend usesrequest.form.get("question"), make sure you're sending a field namedquestion(no typos likequeston). - If your Flask route is expecting JSON data instead of form data, adjust your AJAX call:
And in your Flask route, use$.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); } });request.get_json()to parse the data instead ofrequest.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 yourdatefield 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
correctis 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 (likeYYYY-MM-DD) so SQLAlchemy can convert it to adatetimeobject.
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

