【问题标题】:spring cors blocked on get弹簧 cors 在获取时被阻塞
【发布时间】:2020-04-20 11:51:24
【问题描述】:

在我的 spring 服务器中,我添加了这个来启用 cors:

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/*").allowedOrigins("http://localhost:3000");
            }
        };
    }

在我的 react.js 客户端中,当我 POST 时我没有收到任何错误,但是当我尝试 GET 时,我收到错误消息:

从源“http://localhost:3000”访问“http://localhost:8080/user/aweq”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

代码:

let url=constant.serverURL+"user/"+this.state.username;
axios.get(url).then((res)=>console.log(res));

我什至试过这个:

let url=constant.serverURL+"user/"+this.state.username;
        axios.get(url,
            {headers:
                    {
                        "Content-Type": "application/json"
                    }
            }
        ).then((res)=>console.log(res));

【问题讨论】:

  • 从 axios.get 请求中移除整个 headers 块。 GET 请求中没有请求正文,因此无需为请求设置 "Content-Type": "application/json" 标头。

标签: reactjs spring cors axios


【解决方案1】:

在您的全局配置中,您提供了错误的映射,为了在所有端点上启用 cors,您需要将映射提供为 /**

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }

官方doc

【讨论】:

    【解决方案2】:

    我认为唯一应该解决的是

    registry.addMapping("/**").allowedOrigins("http://localhost:3000");
    

    so from /* => /**, 覆盖路径 /user/{username}

    在此处查找路径中的通配符 https://help.sumologic.com/03Send-Data/Sources/04Reference-Information-for-Sources/Using-Wildcards-in-Paths

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-31
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 2018-07-10
      • 2016-03-31
      相关资源
      最近更新 更多