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。
添加回答
舉報