Angular 7, and Spring Boot App - No 'Access-Control-Allow-Origin' header is present on the requested resource

8.1k Views Asked by At

I have added @CrossOrigin(origins = "*") annotation at the class level to my controller in the Spring Boot app, and I am still getting this error when I make an HTTP GET request from Angular to the Spring Boot app (listening on port 9000). Here is the error I get from Chrome.

Access to XMLHttpRequest at 'http://localhost:9000/employee/all' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1

There are 1 best solutions below

0
Matt On

I've found @CrossOrigin to be extremely finicky. You can try using just @CrossOrigin without any parameters as Alexander suggested.

You can also try adding a custom CorsFilter Bean to the class where you call SpringApplication.run(). That way you've essentially got full control over the filter and can add/remove methods if necessary.

Something like this:

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));

    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}