我正在尝试对基于JSON的API进行POST调用,但是我一直收到Status:400,错误的请求。 这是我当前的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API TEST</title>
</head>
<body>
<button onclick="myFunction()">Test</button>
<div id="result"></div>
<script>
function myFunction() {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
//alert(this.status);
alert(this.readyState);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhr.open("POST", URL);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({username: "test", password: "test"}))
}
</script>
</body>
</html>