【发布时间】:2018-04-17 20:09:27
【问题描述】:
我有一个本地运行的服务器,它有一个内置的 rest api。要通过这个 api 登录,我们需要通过 POST 方法将用户名、密码和组织作为参数发送到 url localhost:8090/ehr/api/v1/login 并且服务器返回一个身份验证令牌作为响应。当我尝试通过以下代码直接执行此操作而无需用户从表单输入时:
<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"
第二个代码有什么问题以及如何更正?
【问题讨论】:
标签: javascript html rest api xmlhttprequest