问题
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