Spring框架HttpMessageNotReadableException:缺少所需的请求正文

时间:2019-12-07 23:35:16

标签: java reactjs spring post axios

我正在尝试在React中向Spring中的后端服务器发出发布请求,但始终出现以下错误:

  

[错误]-   org.springframework.http.converter.HttpMessageNotReadableException:   缺少必需的请求正文。

对邮递员来说效果很好。

react部分的代码:

let testeDTO = JSON.stringify({
  email: "teste@@teste.com",
  senha: "1234",
  grupo: 1
});

axios
  .post("http://192.168.0.49:8080/site/login/", testeDTO, {
    headers: {
      "Content-Type": "application/json"
    }
  })
  .then(response => {
    console.log(response);
  })
  .catch(erro => {
    console.log(erro.response);
  });

其余控制器上的注释:

@RestController
@RequestMapping("/site/login")

Spring的代码:

@PostMapping
public testeDTO login(@RequestBody TesteDTO testeDTO) {

}

CORS类:

@WebFilter(urlPatterns = {"/*"})
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "*, Content-Type, authorization, grupo, usuario");
        filterChain.doFilter(request, response);
    }
}

DTO代码:

public class TesteDTO {

    private String email;
    private String senha;
    private Long grupo;

    //getters and setters
}

1 个答案:

答案 0 :(得分:1)

很明显,axios帖子上的标题需要包装在{}中。因此,过了很长时间,这对我来说还是解决了,留给那些在这个问题上遇到类似问题的人留在这里。

var headers = {
        'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
    };
axios
  .post("http://192.168.0.49:8080/site/login/", testeDTO, {headers})
  .then(response => {
    console.log(response);
  })
  .catch(erro => {
    console.log(erro.response);
  });