问题
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>
回答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),
});
回答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:
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)
来源:https://stackoverflow.com/questions/63488725/json-bad-format-in-post-method