Warm tip: This article is reproduced from serverfault.com, please click

reactjs-如何将CORS添加到spring数据剩余暴露的“ / profile”端点

(reactjs - How do i add CORS to "/profile" endpoint exposed by spring data rest)

发布于 2020-11-28 17:45:03

尝试从React客户端访问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.
Questioner
Suman Mondal
Viewed
11
k-wasilewski 2020-11-29 02:20:35

最简单的方法是@CrossOrign("*")在控制器类上方添加注释。

编辑 另一个方法是通过公开以下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);
}