Spring @CrossOrigin does not work with DELETE method

荒凉一梦 提交于 2019-12-13 14:16:36

问题


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.

回答1:


@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
}


来源:https://stackoverflow.com/questions/44067871/spring-crossorigin-does-not-work-with-delete-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!