删除方法CORS问题在REST控制器中[英] Delete Method Cors issue in Rest Controller

问题描述

我的项目中有一些休息端点,我从另一台服务器中的客户端应用程序调用这些终点.我已经使用@CrossOrigin注释成功禁用了CORS,所有方法都可以正常工作,除了将以下错误在Chrome上丢弃的删除方法:

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

        //...
    }

    }

有什么解决方法?

推荐答案

我找到了一个解决方案,分析了HTTP请求后,我注意到访问控制 - 允许使用方法header缺少删除方法,因此我已通过删除@CrossOrigin注释添加了它,并添加了此bean到配置:

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


                }
            };
        }

其他推荐答案

添加到上面的答案中,禁用CORS无法用于删除的原因(但用于获取和发布)的原因是,这是此处所述的WebMvcconFigurer的默认行为(以黄色突出显示):

在此处输入图像说明

本文地址:https://www.itbaoku.cn/post/978387.html