我有一项与纯 JavaScript 相关的任务,在将数据写入 API 文件时遇到了问题。这是我写的:
document.getElementById('btn').addEventListener("click",function (event) {
event.preventDefault();
var countryName = document.getElementById("name").value;
var countryArea = document.getElementById("area").value;
var countryPopulation = document.getElementById("population").value;
var countryCallingCode = document.getElementById("calling_code").value;
if (countryName !== "" && countryArea !== "" && countryPopulation !== "" && countryCallingCode !== "") {
var postReq = new XMLHttpRequest();
postReq.open('POST', '', true);
var data = {
area: countryArea,
calling_code: countryCallingCode,
created_at: Date.now(),
id: ID,
name: countryName,
population: countryPopulation
};
console.log(data.id);
var jsonPost = JSON.stringify(data);
postReq.onload = function () {
var countries = JSON.parse(postReq.responseText);
if (postReq.readyState == 4 && postReq.status == "201") {
console.log(countries);
}
}
postReq.send(jsonPost);
}
});
但我收到一个错误POST 422 (Unprocessable Entity)
。我也写了获取、删除和编辑功能,它们可以工作,所以我不明白为什么这个不起作用。所以也许有人知道为什么会发生这种情况以及如何解决这个问题?
这是一个示例代码,对我有用:
var data = {};
data.area = 5555;
data.calling_code = "+25";
data.name = "Japan";
data.population = 100000000;
var url = "";
var jsonUpdate = JSON.stringify(data);
console.log(jsonUpdate);
var updateReq = new XMLHttpRequest();
updateReq.open("PUT", url + '/3', true);
updateReq.setRequestHeader('Content-type', 'application/json; charset=utf-8');
updateReq.onload = function () {
var countries = JSON.parse(updateReq.responseText);
if (updateReq.readyState == 4 && updateReq.status == "200") {
console.table(countries);
} else {
console.error(countries);
}
}
updateReq.send(jsonUpdate);