Pankwood
Pankwood

Reputation: 1878

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>

Upvotes: 1

Views: 1798

Answers (3)

codediesel
codediesel

Reputation: 63

I had a issue as well today and the solution I have used was adding encodeURIComponent, as I was building a json to send via GET Request.

const filter = [{
            $or: [{
                name: encodeURIComponent(`${model.get('name')}`),
            }, {
                registered_no_c:`${model.get('company_registration_number_c')}`,
            }]
        }];
        const url = 'Accounts?filter=' + JSON.stringify(filter);

Upvotes: 0

Kevin Hoopes
Kevin Hoopes

Reputation: 507

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),
});

Upvotes: 3

Nadav Halfon
Nadav Halfon

Reputation: 26

Note that you try to make the json string yourself, and that, including a missing , when concating txt is what makes the error. We can fix it but I think you should change the way you implement it.

I recommend using an array instead of concating strings. for example:

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

and then later on just perform JSON.stringify(param)

Upvotes: 0

Related Questions