我正在尝试调用基于json的身份验证API,但无法正常工作。该API接受两个参数作为JSON格式的输入;用户名和密码。
我在做什么错?这是我当前的测试代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>API test</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>API test</h1>
<button id="btn">test</button>
</header>
<p id="result"></p>
<script>
const xhr = new XMLHttpRequest();
xhr.onload = function () {
const serverResponse = document.getElementById("result");
serverResponse.innerHTML = this.responseText;
}
xhr.open("POST", "url");
xhr.setRequestHeader("Content-type", "application/json");
xhr.send("username=test&password=test");
</script>
</body>
</html>
答案 0 :(得分:2)
尝试这个。
xhr.open("POST", "url");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({ username: "test", password: "test" }));