Post方法中的JSON格式错误 [英] JSON bad format in Post method
本文介绍了Post方法中的JSON格式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试提交POST请求,但收到错误状态代码400,因为我发送的数据格式错误,但我不知道该如何格式化.
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.
Web API应该采用这种格式(Web API可以正常工作,如果我通过邮递员发送数据,我不会遇到任何麻烦):
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 }]
这是我发送的:
"["{\"word\": \"Value\", \"box\": 0 }"]"
有什么格式吗?
这是简化的整个代码:
<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>
推荐答案
我认为不需要使用字符串来构建JSON.
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;
然后您可以将它们传递给 JSON.stringify()
,而不用将其包装在数组中.
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),
});
这篇关于Post方法中的JSON格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文