Когда я использую springboot2.2.1 для междоменного разрешения, я обнаруживаю, что запрос OPTIONS возвращает код состояния 400. Та же конфигурация верна, когда используется springboot2.1.6. Фильтр:
@WebFilter("/*")
public class CORSSFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
var request = (HttpServletRequest) servletRequest;
var response = (HttpServletResponse) servletResponse;
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Methods", "GET, OPTIONS, HEAD, PUT, POST,DELETE");
response.addHeader("Access-Control-Allow-Headers", "content-type");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Max-Age", "3600");
chain.doFilter(request, response);
}
}
Контроллер:
@RestController
@RequestMapping
public class TestController {
@PostMapping("/test")
public String test(@RequestBody String username) {
System.out.println("username : " + username);
return username;
}
}
JS:
const datas = {"username":"admin"};
$.ajax(
{
url: "http://localhost:8080/test",
contentType: "application/json;charset=utf-8",
dataType: "json",
type:"POST",
data: JSON.stringify(datas),
success: function(res){
console.info("res : " + JSON.stringify(res));
}, error: function(err){
console.info("error : " + JSON.stringify(err));
}});
Консоль:
Request URL: http://localhost:8080/test
Request Method: OPTIONS
Status Code: 400
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-down
Журнал ошибок:
2019-12-11 15:45:40.138 WARN 89497 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String org.tubetrue01.test.controller.TestController.test(java.lang.String)]