首页 > 解决方案 > REST API 帖子给出 html 响应

问题描述

我的 REST API 有问题,当我从登录表单发出请求 (POST) 时,我收到的是登录 html 而不是用户 JSON。我想问题出在 Spring Security 的配置上,但我不知道如何解决它。我的配置方法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/", "/signin.html","/index.css","/javascript/**", "api/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/signin.html");

}

和后控制器:

@PostMapping("")
public ResponseEntity<Object> save( @RequestBody @Valid UserDto user, BindingResult result){
    if(user.getId() != null)
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "User cannot be saved");
    System.out.println(result);
    if(result.hasErrors()){
        List<ObjectError> errors = result.getAllErrors();
        errors.forEach(err -> System.out.println(err.getDefaultMessage()));
        return ResponseEntity.badRequest().body(errors);
    }
    UserDto savedUser = userService.save(user);
    URI location = ServletUriComponentsBuilder
            .fromCurrentRequest()
            .path("{id}")
            .buildAndExpand(savedUser.getId())
            .toUri();
    return ResponseEntity.created(location).body(savedUser);
}

为 /api/users 发出请求。有人可以帮忙吗?

标签: javaspringrestsecurity

解决方案


推荐阅读