Spring boot在通过站点发送但不与邮递员一起发送时拒绝正文

问题描述 投票:0回答:2

嘿,我正在使用弹簧靴,发生了一些奇怪的事情。我想向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}

Web请求

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]]


javascript java spring spring-boot
2个回答
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);
}

0
投票

您需要使用异步请求。您已经在使用jquery,它在$.ajax()中提供了此功能,无需使用javascript的内置XMLHttpRequest。

© www.soinside.com 2019 - 2024. All rights reserved.