Tengo algunos puntos finales Rest en mi proyecto a los que llamo desde una aplicación cliente en otro servidor. He deshabilitado con éxito Cors usando la anotación @CrossOrigin , y todos los métodos funcionan bien, excepto el método Eliminar, que arroja el siguiente error en Chrome:
XMLHttpRequest cannot load http://localhost:8856/robotpart/1291542214/compatibilities. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8888' is therefore not allowed access. The response had HTTP status code 403.
Aquí está mi controlador:
@CrossOrigin(origins = "*") @ExposesResourceFor(RobotPart.class) public class RobotPartController { //All endpoints are working except the Delete Mapping @GetMapping("/robotpart") public ResponseEntity<List<RobotPartResource>> listAllParts() { //.. } @GetMapping("/robotpart/{id}") public ResponseEntity<RobotPartResource> getById(@PathVariable Integer id) { //.. } @GetMapping("/robotpart/{id}/compatibilities") public ResponseEntity<Collection<RobotPartResource>> getRobotCompatibilities(@PathVariable Integer id, //.. } @PostMapping("/robotpart") public ResponseEntity<RobotPartResource> getById(@RequestBody @Valid RobotPart newRobot) { //.. @PutMapping("/robotpart/{id}") public ResponseEntity<RobotPartResource> modify(@PathVariable Integer id, @Valid @RequestBody RobotPart newRobot) { //... } @DeleteMapping("/robotpart/{id}") public ResponseEntity<RobotPart> deleteById(@PathVariable Integer id) { //... } }¿Alguna forma de evitarlo?
Encontré una solución, después de analizar las solicitudes http, noté que al encabezado Access-Control-Allow-Methods le faltaba el método DELETE, así que lo agregué eliminando la anotación @CrossOrigin y agregando este bean a la configuración:
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/robotpart/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE"); } }; }Agregando a las respuestas anteriores, la razón por la cual deshabilitar CORS no funcionará para DELETE (pero funciona para GET y POST) es que este es el comportamiento predeterminado para WebMvcConfigurer como se indica aquí (resaltado en amarillo):