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

Error 400 in axios when i try connect to Spring MVC

嗨,我正在尝试在 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);
}
}

此外,当使用邮递员使用 restService 时,我得到响应

correct

您使用 Axios 发送的 username/password 是请求负载的一部分(可以通过 Spring 端的 @RequestBody 访问)。

如果你想让你的代码正常工作,你必须传递 username/password 作为查询字符串。

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

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

您应该将 @RequestBody 与包含 2 String 字段(用户、密码)的 UserInfo class 一起使用,而不是您的 @RequestParam