2 回答
TA贡献1898条经验 获得超8个赞
查看您的响应 JSON 是否包含该response字段。
根据日志,收到的响应是{"Username":"a", "Password":"a"}在您正在执行的 JS 代码中data.response.toString(),因为响应未定义。你收到Uncaught TypeError: Cannot read property 'response' of undefined错误了。
我尝试了以下代码,它在我的系统上运行:
$(document).ready(function() {
$("#LoginButtonID").click(function(){
var link = "http://localhost:9024/login/auth";
var body = "{"+
"\"Username\":\""+document.getElementById("UserNameID").value+"\", " +
"\"Password\":\""+document.getElementById("PasswordID").value+"\"" +
"}";
sendRequest(link,'POST',body);
if(data.response.toString()===("valid and successful")){
localStorage.setItem("username",document.getElementById("UserNameID").value);
alert("done!")
}else if(data.response.toString()===("failed to authenticate")){
alert("failed to login");
}
})
});
function sendRequest(link, type, body) {
var xhr = new XMLHttpRequest();
xhr.open(type, link, false);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 202 ) {
data = JSON.parse(xhr.responseText);
}else if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 401 ){
data = JSON.parse(xhr.responseText); }
}
xhr.send(body);
}
控制器代码:
@CrossOrigin(maxAge = 3600)
@PostMapping("auth")
@ResponseBody
public ResponseEntity<?> authenticate(@RequestBody Map<String, String> body) {
// sending some response for the sake of testing
body.put ("response","valid and successful");
return new ResponseEntity<>(body, HttpStatus.ACCEPTED);
}
TA贡献1776条经验 获得超12个赞
您需要使用异步请求。您已经在使用 jquery,它在$.ajax()中提供了此功能,无需使用 javascript 的内置 XMLHttpRequest。
添加回答
举报