Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

Spring Boot CORS issue

I am trying to learn spring with this tutorial:

https://spring.io/guides/tutorials/react-and-spring-data-rest/

but I am doing frontend app as a separate app. While making a call to: http://localhost:8080/api/employees

how to enable CORS globally ? thanks!

Tried in Application with:

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

but it does not help

did some testing with custom @RestController like here:

https://spring.io/guides/gs/rest-service-cors/#global-cors-configuration and calling http://localhost:8080/api/greeting from external frontend app works fine, only those rest endpoints CRUD auto generated via spring are not allowed CORS there.. How to avoid this issue ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try adding this to your main application class file:

    @Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...