4

I'm working on graphQL and spring boot project. The API works well using graphiQL but when trying to consume it using Apollo vueJS, it causes CORS origin error.

I'm using @CrossOrigin annotation in ProductQuery class which implements GraphQLQueryResolver like below:

 @CrossOrigin(origins = "https://localhost:8081")
public List<Product> getProducts(){return this.productService.findAll(); } 

Here is the error displayed on frontEnd project: CORS origin error

I appreciate your help.

Sihem Hcine
  • 1,089
  • 5
  • 24
  • 40

5 Answers5

3

For local development you may need a CorsFilter bean to enable your local origin:

@Configuration
@Profile("local")
public class LocalCorsConfiguration {

  @Bean
  public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://localhost:3000");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/graphql/**", config);
    return new CorsFilter(source);
  }
}

Don't forget to start the application with -Dspring.profiles.active=local.

Dani R
  • 551
  • 1
  • 4
  • 15
1

What worked for me was the solution explained in the official docs

My version of a configurer bean looks like this:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(final CorsRegistry registry) {
            registry.addMapping("/graphql/**")
                    .allowedOrigins(CorsConfiguration.ALL)
                    .allowedHeaders(CorsConfiguration.ALL)
                    .allowedMethods(CorsConfiguration.ALL);
        }
    };
}
1

Since Spring Boot 2.7.0 there are configuration properties for CORS with GraphQL:

spring:
  graphql:
    cors:
      allow-credentials: true
      allowed-origins:
        - http://localhost:3000

See GraphQlCorsProperties.java for further properties.

Rollozuh
  • 105
  • 1
  • 8
0

To solve this issue you need to add this in your application properties graphql.servlet.corsEnabled: true after that your server response header will have the CORS properties.

0

I had the same issue. My solution is a "remake" of whipper slapper's answer. The docs are saying, that you need to add the corsConfigurer-@Bean to your Application Class. This is, what it looks like in Kotlin:

@Bean
fun corsConfigurer(): WebMvcConfigurer {
    return object : WebMvcConfigurer {
        override fun addCorsMappings(registry: CorsRegistry) {
            registry.addMapping("/graphql/**")
                .allowedOrigins(CorsConfiguration.ALL)
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
        }
    }
}
Julius Babies
  • 955
  • 3
  • 6
  • 22