-1

I tried doing this but it isn't working. I also tried adding @CrossOrigin on top of my controller class but that didn't work either.

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");         //'*' allows all endpoints, Provide your URL/endpoint, if any.
        config.addAllowedHeader("*");
        config.addAllowedMethod("POST");   //add the methods you want to allow like 'GET', 'PUT',etc. using similar statements.
        config.addAllowedMethod("GET");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

error

GodLike
  • 19
  • 5

2 Answers2

-1

There are several ways to achieve that. You can do that on method level or global. For Example (source: https://www.baeldung.com/spring-cors):

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
@EnableWebMvc
public class CorsConfiguration implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST");
    }
}

also take a look on the old thread: How to configure CORS in a Spring Boot + Spring Security application?

Christian
  • 152
  • 1
  • 13
-1
@Configuration
public class CorsConfig {

@Bean
public WebMvcConfigurer corsConfig() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
                    .allowedOrigins("*")
                    .allowedHeaders("*")
                    .allowCredentials(false);
        }
    };
}

}

Try this once, it should work.

Suraj Gautam
  • 1,524
  • 12
  • 21
  • The bean 'corsConfig', defined in class path resource [perosnal/spotifymatcher/util/CorsConfig.class], could not be registered. A bean with that name has already been defined in file [D:\IdeaProjects\spotifymatcher\target\classes\perosnal\spotifymatcher\util\CorsConfig.class] and overriding is disabled. – GodLike Apr 22 '22 at 07:35
  • Please do mvn clean install if you are using maven. gradle clean build if gradle and try. – Suraj Gautam Apr 22 '22 at 08:36
  • Tried that too, same error – GodLike Apr 22 '22 at 09:54