【问题标题】:Delete Method Cors issue in Rest Controller在 Rest Controller 中删除方法 Cors 问题
【发布时间】:2023-04-03 22:37:01
【问题描述】:

我的项目中有一些 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<RobotPartResource>> listAllParts() {
        //..
    }

    @GetMapping("/robotpart/{id}")
    public ResponseEntity<RobotPartResource> getById(@PathVariable Integer id) {
        //..
    }


    @GetMapping("/robotpart/{id}/compatibilities")
    public ResponseEntity<Collection<RobotPartResource>> getRobotCompatibilities(@PathVariable Integer id,
          //..
    }


    @PostMapping("/robotpart")
    public ResponseEntity<RobotPartResource> getById(@RequestBody @Valid RobotPart newRobot) {
        //..

    @PutMapping("/robotpart/{id}")
    public ResponseEntity<RobotPartResource> modify(@PathVariable Integer id, @Valid @RequestBody RobotPart newRobot) {

         //...
    }

    @DeleteMapping("/robotpart/{id}")
    public ResponseEntity<RobotPart> deleteById(@PathVariable Integer id) {

        //...
    }

    }

有什么办法吗?

【问题讨论】:

    标签: java spring spring-mvc spring-boot cors


    【解决方案1】:

    我找到了一个解决方案,在分析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");
    
    
                    }
                };
            }
    

    【讨论】:

      猜你喜欢
      • 2011-07-05
      • 1970-01-01
      • 2019-05-22
      • 2016-05-14
      • 2021-09-19
      • 2014-07-19
      • 1970-01-01
      • 2020-05-06
      • 2021-07-26
      相关资源
      最近更新 更多