【发布时间】:2020-08-19 14:02:40
【问题描述】:
我正在尝试提交 POST 请求,但我收到错误状态代码 400,因为我发送的数据格式错误,但我不知道如何格式化。
Web API 需要这种格式(Web API 工作正常,如果我通过 Postman 发送数据就没有任何问题):
[{ "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>
【问题讨论】:
-
你为什么要这样做
body: JSON.stringify([params]),而不是body: JSON.stringify(params),? -
编写自己的 json 生成方法是一个直接的危险信号。绝对没有理由这样做。
-
在不久的将来我会发送这样的数据:
[ { "word": "string", "box": 0 }, { "word": "string2", "box": 0 } ]但我不认为这是问题,不是吗? -
我正在尝试自己处理代码,但您调用的 api 似乎对公众不可用。即:本地主机:44312。你有这个 API 的公开版本吗?
标签: javascript http-post http-status-code-400