Search code examples
javascripthttp-posthttp-status-code-400

JSON bad format in Post method


I'm trying to submit a POST request, but I got error status code 400 because the data I'm sending is in bad format but I don't know how to format that.

The web API expected this format(The web API is working perfectly, if I send the data by Postman I don't have any trouble):

[{ "word": "string", "box": 0 }]

And this is what I am sending:

"["{\"word\": \"Value\", \"box\": 0 }"]"

Any idea how to format it?

This is the entire code simplified:

<form onsubmit="handlePostSubmit()" id="formPost">

  <div>
    <input type="checkbox" id="chk01" name="ckbWord" value="Value" defaultChecked></input>
    <label for="chk01"> value</label>
  </div>

  <button type="submit" form="formPost" value="Submit">Submit</button>
</form>

<script>
function getWords() {
  const words = document.forms[0];
  var txt = "";
  for (var i = 0; i < words.length; i++) {
    if (words[i].checked) {
      txt += '{"word": "' + words[i].value + '", "box": 0 }';
    }
  }
  return txt;
}

function handlePostSubmit() {
//  params.preventDefault();

  const words = getWords();
  alert(words);
  var x = create(words)
            .then(() => {
                //TODO: Msg of ok or error
    alert("Ok")
            });
  alert(x);
}

async function create(params) {
    const response = await fetch("https://localhost:44312/words", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify([params]),
    });
    if (response.ok) {
        const resposta = await response.json();
        return resposta;
    }
    throw new Error('Error to save words');
}
</script>

Solution

  • I think there's no need to use strings to build your JSON.

    You can simply push objects, like so:

    const wordsFromDoc = document.forms[0]
    const words = []
    for (var i = 0; i < words.length; i++) {
       if (words[i].checked) {
         words.push({ word: words[i].value, box: 0 });
       }
    }
    
    return words;
    

    And then you can just pass those along and JSON.stringify() it later without wrapping it in an array.

    const response = await fetch("https://localhost:44312/words", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
    });