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:

I appreciate your help.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With