ローカルに実行されているサーバがあり、残りのAPIが組み込まれています。このapiを使ってログインするには、url localhost:8090/ehr/api/v1/loginへのパラメータとしてusername、password、organizationをPOSTメソッド経由で送信し、サーバが応答としてauthトークンを返す必要があります。私は、次のコードをフォームからユーザーの入力なしで、直接これを実行しようとすると:Javascript xmlhttpフォームからapiリクエストを送信する
は<html>
<body>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=admin&password=admin&organization=123456");
</script>
</body>
</html>
それは完全に正常に動作し、認証トークンがJSONとして返されますが、私は次を経由してユーザーフォームの入力を通じて同じことをしようとした場合コード:
<html>
<body>
<form method="POST">
<input type="text" name="username" id="username" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="text" name="organization" id="organization" placeholder="Organization">
<button id="submit" onclick="login()">Let me in!</button>
<br><br>
</form>
<script type="text/javascript">
function login() {
var user=document.getElementById("username").value;
var pass = document.getElementById("password").value;
var org = document.getElementById("organization").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "username="+user+"&password="+pass+"&organization="+org;
xhttp.send(param);
}
</script>
</body>
</html>
このコードはスローエラーが
login.html:26 XHR failed loading: POST "http://localhost:8090/ehr/api/v1/login"
第二のコードとどのようにそれを修正するための何が問題になっているのですか?