gpt4 book ai didi

java - 当我尝试连接到 Spring MVC 时,axios 中出现错误 400

转载 作者:行者123 更新时间:2023-12-02 12:21:36 25 4
gpt4 key购买 nike

嗨,我正在尝试在 html 中进行登录,并使用 axios 将用户和密码发送到 @RestController 和 @PostMapping,此时,我得到了对服务器的响应,但问题是客户端中的响应,因为我得到当我尝试在日志中打印响应时出现错误 400。

Axios:

var url = 'rest/loginParametros';
axios.post(url, {
user: this.username,
password: this.password
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

请求映射

@org.springframework.web.bind.annotation.RestController
@RequestMapping("/rest")
public class RestController {

private final Log log = LogFactory.getLog(RestController.class);

@PostMapping("/loginParametros")
public ResponseEntity<Boolean> loginParametros(@RequestParam(value = "user", required = true) String user,
@RequestParam(value = "password", required = true) String password)
{
log.info("user: " + user + " password: " + password);
if(user.equals("hitzu") && password.equals("hitzu"))
return new ResponseEntity<>(true, HttpStatus.OK);
return new ResponseEntity<>(false, HttpStatus.OK);
}
}

此外,当与 postman 一起使用restService时,我得到了响应

correct

最佳答案

您使用 Axios 发送的用户名/密码是请求负载的一部分(在 Spring 端可通过 @RequestBody 访问)。

如果您想让代码正常工作,您必须将用户名/密码作为查询字符串传递。

var url = 'rest/loginParametros?user=' + this.username + '&password=' + this.password;

但出于安全考虑,我不建议使用它。

您应该使用@RequestBodyUserInfo包含 2 String 的类字段(用户、密码)而不是您的 @RequestParam s。

关于java - 当我尝试连接到 Spring MVC 时,axios 中出现错误 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45740803/

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