如何将 CORS 添加到 Spring 数据休息公开"/profile"端点



我在尝试访问/配置文件";spring数据rest公开的端点。我已经在存储库中启用了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("*")注释。

edit另一种方法是通过公开这个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);
}

最新更新