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

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

  1. Build an array of objects instead of a string in getWords()
  2. Prevent the form's default submission behavior (you had this commented out, which causes the page to refresh and cancel your AJAX call)
  3. 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 the event parameter and called event.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 uses JSON.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:58:16