我如何将 CORS 添加到 spring data rest 公开的“/profile”端点
How do i add CORS to "/profile" endpoint exposed by spring data rest
我在尝试从反应客户端访问 spring-data-rest 公开的“/profile”端点时收到以下错误。我在存储库中启用了 CORS,但仍然出现错误,同时我能够访问“http://localhost:8083/merchants”。提前致谢。
错误:
Access to XMLHttpRequest at 'http://localhost:8083/profile/merchants' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
最简单的方法是在控制器上方添加一个@CrossOrign("*")
注解class。
编辑
另一种方法是通过公开此 bean 在全局启用 CORS:
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// Don't do this in production, use a proper list of allowed origins
config.setAllowedOrigins(Collections.singletonList("*"));
config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
我在尝试从反应客户端访问 spring-data-rest 公开的“/profile”端点时收到以下错误。我在存储库中启用了 CORS,但仍然出现错误,同时我能够访问“http://localhost:8083/merchants”。提前致谢。
错误:
Access to XMLHttpRequest at 'http://localhost:8083/profile/merchants' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
最简单的方法是在控制器上方添加一个@CrossOrign("*")
注解class。
编辑 另一种方法是通过公开此 bean 在全局启用 CORS:
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// Don't do this in production, use a proper list of allowed origins
config.setAllowedOrigins(Collections.singletonList("*"));
config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}