在Rest Controller中删除方法Cors问题
我的项目中有一些Rest端点,我从另一台服务器的客户端应用程序调用。 我已经使用@CrossOrigin
注释成功禁用了Cors,除了在Chrome上引发以下错误的Delete方法之外,所有方法都正常工作:
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.
这是我的控制器:
@CrossOrigin(origins = "*") @ExposesResourceFor(RobotPart.class) public class RobotPartController { //All endpoints are working except the Delete Mapping @GetMapping("/robotpart") public ResponseEntity<List> listAllParts() { //.. } @GetMapping("/robotpart/{id}") public ResponseEntity getById(@PathVariable Integer id) { //.. } @GetMapping("/robotpart/{id}/compatibilities") public ResponseEntity<Collection> getRobotCompatibilities(@PathVariable Integer id, //.. } @PostMapping("/robotpart") public ResponseEntity getById(@RequestBody @Valid RobotPart newRobot) { //.. @PutMapping("/robotpart/{id}") public ResponseEntity modify(@PathVariable Integer id, @Valid @RequestBody RobotPart newRobot) { //... } @DeleteMapping("/robotpart/{id}") public ResponseEntity deleteById(@PathVariable Integer id) { //... } }
有什么办法吗?
我找到了一个解决方案,在分析了http请求之后,我注意到Access-Control-Allow-Methods标头缺少DELETE方法,所以我通过删除@CrossOrigin
注释添加它,并将此bean添加到配置中:
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/robotpart/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE"); } }; }
- 如何将Cross Origin资源共享与Spring MVC 4.0.0 RESTful Webservice集成
- 使用Spring Framework为OPTIONS请求启用CORS
- Google App Engine和CORS
- GWT HTTP请求响应代码0,CORS正在工作
- IE11 CORS拒绝https上的OPTIONS
- RESTful webservice:如何在java中设置头文件以接受Access-Control-Allow-Origin允许的XMLHttpRequest
- 使用Java Config的全局CORS配置不起作用
- 在预检响应中,Access-Control-Allow-Methods不允许使用方法DELETE
- Access-Control-Allow-Origin在ajax调用泽西restWeb服务中