Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable CORS origin graphql

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.

like image 492
Sihem Hcine Avatar asked Aug 01 '26 09:08

Sihem Hcine


2 Answers

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.

like image 175
Dani R Avatar answered Aug 02 '26 22:08

Dani R


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.

like image 39
Rollozuh Avatar answered Aug 02 '26 23:08

Rollozuh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!