Spring @CrossOrigin does not work with DELETE method
Asked Answered
C

2

7

Spring @CrossOrigin annotation does not work with DELETE methods.

Example code (in Groovy):

@CrossOrigin
@RestController
@RequestMapping('/rest')
class SpringController {

    @RequestMapping(value = '/{fileName}', RequestMethod.DELETE)
    void deleteFile(@PathVariable fileName) {
        // logic
    }

}

For this code I get the exception:

XMLHttpRequest cannot load http://localhost:8080/rest/filename.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.

Notes:

  • I tested it in Chrome 58 and Postman 4.10.7
  • According to https://spring.io/guides/gs/rest-service-cors/ by default @CrossOrigin allows only GET, HEAD and POST cross-origin requests. Although specifying @CrossOrigin(methods = [RequestMethod.GET, RequestMethod.DELETE]) did not help
  • I omitted some code for brevity. Actual controller also has GET request by the same mapping, delete method has return type and produces JSON response, and other minor stuff that I don't think affects the issue.
Cristoforo answered 19/5, 2017 at 10:37 Comment(3)
“The response had HTTP status code 404.”Pori
@Pori if I use GET request by the same URL it works and returns the file so I don't see where to look further in this direction.Cristoforo
@Marged I can't test it since it is not yet deployed anywhere and I can't do that now.Cristoforo
W
0
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
      registry.addMapping("your cross origin url")
            .allowedOrigins("your cross origin host/url")
            .allowedHeaders("Access-Control-Allow-Origin", "*")
            .allowedHeaders("Access-Control-Allow-Headers", "Content-Type,x-requested-with").maxAge(20000)
            .allowCredentials(false)
            .allowedMethods("DELETE");
 }
}

// in your controller
@RequestMapping(value = '/{fileName:.+}', RequestMethod.DELETE)
void deleteFile(@PathVariable fileName) {
    // your custom logic
}
Whew answered 19/5, 2017 at 11:49 Comment(0)
C
0
@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
            .allowedOrigins("*")
            .allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
        }
    };
}
Coloring answered 22/12, 2021 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.