删除静止控制器中的方法 Cors 问题

2022-09-03 08:53:56

我的项目中有一些 Rest 终结点,我从另一台服务器的客户端应用程序调用这些终结点。我已经使用注释成功禁用了Cors,并且除了在Chrome上抛出以下错误的Delete方法外,所有方法都工作正常:@CrossOrigin

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) {

        //...
    }

    }

有什么办法可以解决这个问题吗?


答案 1

我找到了一个解决方案,在分析了http请求之后,我注意到Access-Control-Allow-Methods标头缺少DELETE方法,所以我通过删除注释并将其添加到配置中来添加它:@CrossOrigin

        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/robotpart/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE");


                }
            };
        }

答案 2

除了上面的答案之外,禁用CORS不适用于DELETE(但适用于GET和POST)的原因是,这是WebMvcConfigurer的默认行为,如下所示(以黄色突出显示):

enter image description here