我正在研究graphQL和spring boot项目。该API使用graphiQL效果很好,但是当尝试使用Apollo vueJS进行使用时,会导致CORS源错误。
我在ProductQuery类中使用@CrossOrigin注释,该注释实现了GraphQLQueryResolver,如下所示:
@CrossOrigin(origins = "https://localhost:8081")
public List<Product> getProducts(){return this.productService.findAll(); }
感谢您的帮助。
答案 0 :(得分:0)
您需要在spring-boot配置中定义CORS过滤器:
@Configuration
public class CORSFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, sec-websocket-protocol, sec-websocket-extensions, sec-websocket-key, sec-websocket-version");
response.addHeader("Access-Control-Max-Age", "3600");
filterChain.doFilter(request, response);
}
}
还需要自定义HttpSecurity配置:
@Configuration
@EnableWebSecurity
public class SpringWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().cors().and()
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
}
}
答案 1 :(得分:0)
要解决此问题,您需要在服务器响应标头具有CORS属性之后,将其添加到应用程序属性graphql.servlet.corsEnabled: true
中。
答案 2 :(得分:0)
对于本地开发,您可能需要一个 CorsFilter
bean 来启用您的本地源:
@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);
}
}
不要忘记使用 -Dspring.profiles.active=local
启动应用程序。