gpt4 book ai didi

javascript - 当站点发送但不通过 postman 发送时,Spring Boot 会拒绝正文

转载 作者:行者123 更新时间:2023-12-01 23:41:49 24 4
gpt4 key购买 nike

嘿,我正在使用 Spring Boot,但发生了一些奇怪的事情。我想向我的 springboot 服务器发出发布请求,当我通过 postman 执行此操作时我成功,但当我通过我的网站执行此操作时失败。我尝试将其更改为不同的 HTTP 请求和数据模型,但出现相同的错误。我送来的尸体和我亲眼所见、测试过的似乎并没有什么不同。错误堆栈跟踪位于 Web 请求中(一直向下)。

我的 Controller 代码

    @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));
}

postman 回复:

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


最佳答案

查看您的响应 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);
}

Controller 代码:

@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);
}

关于javascript - 当站点发送但不通过 postman 发送时,Spring Boot 会拒绝正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58255609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com