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 fo
Solution 1:
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),
});
Solution 2:
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:
functiongetWords() {
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)
Post a Comment for "Json Bad Format In Post Method"