在Rest Controller中删除方法Cors问题 [英] Delete Method Cors issue in Rest Controller

查看:385
本文介绍了在Rest Controller中删除方法Cors问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some Rest endpoints in my project which I call from a client application in another server. I have successfully disabled Cors using the @CrossOrigin annotation, and all the methods work fine except the Delete method which throws the following error on Chrome:

XMLHttpRequest无法加载http:// localhost:8856 / robotpart / 1291542214 /兼容性。对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin标头。因此,不允许来源http://127.0.0.1:8888访问。响应的HTTP状态代码为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请求之后,我注意到Access-Control-Allow-Methods标头缺少DELETE方法,所以我通过删除 @CrossOrigin 注释,并将此bean添加到配置中uration:

I found a solution, after analyzing http requests, I noticed that Access-Control-Allow-Methods header was missing the DELETE method, so I have added it by delete the @CrossOrigin annotation, and adding this bean to the configuration:

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


                }
            };
        }

这篇关于在Rest Controller中删除方法Cors问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆