嘿,我正在用弹簧靴工作,发生了一些奇怪的事情。我想向springboot服务器发出发布请求,当我通过邮递员完成请求时成功,但是当我通过网站进行请求时失败。我试图将其更改为不同的HTTP请求和数据模型,但出现相同的错误。我所送去的尸体与我所观察和测试过的尸体似乎没有差异。错误stacktrace在Web请求中(一直向下)。
我的控制器代码
@CrossOrigin(maxAge = 3600)
@RequestMapping(value = "/auth", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> authenticate(@RequestBody Map<String, String> body) {
System.out.println(body);
ResponseModel responseModel;
ProfileResource login = new ProfileResource();
login.setUsername(body.get("Username"));
login.setPassword(body.get("Password"));
// other code..
responseModel.setData(login);
return new ResponseEntity<>(responseModel, HttpStatus.ACCEPTED);
}
我的JS代码:
$(document).ready(function() {
$("#LoginButtonID").click(function(){
if($('#LoginButtonID').is(':visible')) {
var link = "http://localhost:9024/login/auth";
var body = "{"+
"\"Username\":\""+document.getElementById("UserNameID").value+"\", " +
"\"Password\":\""+document.getElementById("PasswordID").value+"\"" +
"}";
console.log(body);
sendRequest(link,'POST',body);
console.log(data)
if(data.response.toString()===("valid and successful")){
localStorage.setItem("username",document.getElementById("UserNameID").value);
window.location.href = "../html/UserPages/Welcome.html";
}else if(data.response.toString()===("failed to authenticate")){
alert("failed to login");
}
}
})
});
function sendRequest(link, type, body) {
// http request sent to the server in hopes that it will take it
var xhr = new XMLHttpRequest();
xhr.open(type, link, false);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
// once the request was sent and received we then make use of the response
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 202 ) {
data = JSON.parse(xhr.responseText);
console.log("data: " + data.response.toString());
}else if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 401 ){
console.log("Auth failed")
data = JSON.parse(xhr.responseText); }
}
xhr.send(JSON.stringify(body));
}
邮递员回复:
{
"successful": true,
"responseCode": 0,
"response": "valid and successful",
"data": {
"name": null,
"password": null,
"username": "a",
"email": null
}
}
console (IDE) output:
{Username=a, Password=a}
网络请求
login.js:12 {"Username":"a", "Password":"a"}
login.js:47 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
sendRequest @ login.js:47
(anonymous) @ login.js:13
dispatch @ jquery-3.1.1.js:5201
elemData.handle @ jquery-3.1.1.js:5009
login.js:65 POST http://localhost:9024/login/auth 500
sendRequest @ login.js:65
(anonymous) @ login.js:13
dispatch @ jquery-3.1.1.js:5201
elemData.handle @ jquery-3.1.1.js:5009
login.js:14 undefined
login.js:15 Uncaught TypeError: Cannot read property 'response' of undefined
at HTMLButtonElement.<anonymous> (login.js:15)
at HTMLButtonElement.dispatch (jquery-3.1.1.js:5201)
at HTMLButtonElement.elemData.handle (jquery-3.1.1.js:5009)
Console (IDE) output:
2019-10-06 04:36:56.730 WARN 24332 --- [nio-9024-exec-4] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `java.util.LinkedHashMap` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"Username":"a", "Password":"a"}'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `java.util.LinkedHashMap` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"Username":"a", "Password":"a"}')
at [Source: (PushbackInputStream); line: 1, column: 1]]
答案 0 :(得分:0)
您需要使用异步请求。您已经在使用jquery,它在$.ajax()中提供了此功能,无需使用javascript的内置XMLHttpRequest。
答案 1 :(得分:0)
查看您的响应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);
}