POST请求400状态码:数据格式错误排查与修正求助
Fixing the 400 Bad Request for Your POST API Call
Let's break down what's going wrong here and fix it step by step:
The Root Problem
Your current code builds a string of JSON object fragments instead of a proper JavaScript array of objects. When you pass that string to JSON.stringify([params]), you end up with a JSON array containing a single messy string (like "["{\"word\": \"Value\", \"box\": 0 }"]"), which doesn't match the API's expected format of [{ "word": "string", "box": 0 }]—an array of actual structured objects.
Key Fixes to Apply
- Build an array of objects instead of a string in
getWords() - Prevent the form's default submission behavior (you had this commented out, which causes the page to refresh and cancel your AJAX call)
- Correctly stringify the object array for the request body
Corrected Full Code
<form onsubmit="handlePostSubmit(event)" id="formPost"> <div> <input type="checkbox" id="chk01" name="ckbWord" value="Value" defaultChecked> <label for="chk01"> value</label> </div> <!-- Add more checkboxes here if needed --> <button type="submit" form="formPost" value="Submit">Submit</button> </form> <script> function getWords() { const wordsForm = document.forms[0]; const selectedWords = []; // Initialize empty array to hold our objects for (let i = 0; i < wordsForm.length; i++) { // Only process checked checkboxes if (wordsForm[i].checked && wordsForm[i].type === "checkbox") { // Push a proper object into the array, not a string selectedWords.push({ word: wordsForm[i].value, box: 0 }); } } return selectedWords; } function handlePostSubmit(event) { event.preventDefault(); // Critical: stop the form from reloading the page const selectedWords = getWords(); create(selectedWords) .then(() => { alert("Words saved successfully!"); }) .catch(error => { alert(`Error: ${error.message}`); // Gracefully handle errors }); } async function create(wordsArray) { const response = await fetch("https://localhost:44312/words", { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(wordsArray), // Stringify the object array directly }); if (!response.ok) { throw new Error('Failed to save words'); } return await response.json(); } </script>
What Changed?
getWords(): Now creates an array of JavaScript objects instead of concatenating strings. This ensures we have the right data structure before converting to JSON.handlePostSubmit(event): Added theeventparameter and calledevent.preventDefault()to stop the form's default refresh behavior. Also added a.catch()block to handle errors properly instead of assuming success.create(wordsArray): Takes the object array directly and usesJSON.stringify(wordsArray)to produce the exact format the API expects:[{ "word": "Value", "box": 0 }].
This should resolve the 400 Bad Request error since your request body will now perfectly match the API's required schema.
内容的提问来源于stack exchange,提问作者Pankwood
相关产品推荐
相关产品推荐

