-1

I can get,post and update resources from my ReactApp (localhost:3000) to my Spring ApiRest (localhost:8080) but can't delete a resource because CORS policy

I've build a mini app trying to consume a Spring Api Rest from a React app. trying delete a resource returns the next error: it happens both axios and fetchApi


Access to XMLHttpRequest at
'http://localhost:8080/api/borrar-producto/[object%20Object]' from
origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: It
does not have HTTP ok status.


here is my controller

@RestController
@RequestMapping("/api")
public class ProductoControlador {

@RequestMapping(path = "/borrar-producto/{id}")
public ResponseEntity<String> eliminarProducto(@PathVariable Long id) {
  servicio.borrarProducto(id);
  return new ResponseEntity<String>("Se eliminó el producto", HttpStatus.OK);
}
}

here is the config file:

@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedOrigins("*")
            .allowedHeaders("*");
  }
}

and this is the request

  const borrarProducto = async (id) =>{
try {
  axios.delete('http://localhost:8080/api/borrar-producto/' + id)
  .then((res) => console.log(res))
} catch (error) {
  console.log(error);
}

};


i've tried put the @CrossOrigin on method with the params (origins="*", methods{RequestMethod.DELETE}) and also doesn't work

somebody can give me a clue?

  • Please post code for your question not just links to pictures of code. – Mark Schultheiss Mar 27 '23 at 21:42
  • Does this answer your question? [Response for preflight does not have HTTP ok status in angular](https://stackoverflow.com/questions/52047548/response-for-preflight-does-not-have-http-ok-status-in-angular) – GreyBeardedGeek Mar 27 '23 at 22:21
  • @GreyBeardedGeek Thanks! I understand how OPTIONS method works on preflight requests but still cant solve my specific problem. I'll use a PUT method and Logic for delete resources(kind of giving up ). I found that a lot of restApis deletes resources that way. – Agustín Sosa Mar 28 '23 at 23:22
  • Sorry, I missed that you used RequestMapping on the controller method. You probably could have fixed this by using DeleteMapping instead. – GreyBeardedGeek Mar 29 '23 at 11:33

1 Answers1

1

I solved the issue adding these annotations on the controller, it works even without allows the OPTIONS method...

@CrossOrigin(origins = "http://localhost:3000", methods = {RequestMethod.PUT,RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE})