Issue with CORS and error and Access-Control-Allow-Origin header
You can try adding CORS mapping in the application class in this way:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/v1/**")
.allowedHeaders("*")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.maxAge(3600);
}
};
}
https://spring.io/guides/gs/rest-service-cors/
Assuming you work with SpringBoot security:
Add the following in your configuration class (which extends WebSecurityConfigurerAdapter and has @EnableWebSecurity annotation), add cors configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
//other config
}
//TODO needs to be secured on domain you wants to allow
@Bean CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
I had it working with this configuration
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:4200");
}
};
}
}