Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为Spring数据Rest启用跨源资源共享_Spring_Spring Mvc_Spring Data Rest - Fatal编程技术网

为Spring数据Rest启用跨源资源共享

为Spring数据Rest启用跨源资源共享,spring,spring-mvc,spring-data-rest,Spring,Spring Mvc,Spring Data Rest,我正在用Spring4.2.1版本开发Spring(非引导)应用程序。我已经在web配置文件中为SpringMVC启用了CORS @Configuration @EnableWebMvc @ComponentScan({"com.hello.web", "com.hello.rest"}) @Import(RestMvcConfig.class) public class WebConfig extends WebMvcConfigurerAdapter { @Bean public View

我正在用Spring4.2.1版本开发Spring(非引导)应用程序。我已经在web配置文件中为SpringMVC启用了CORS

@Configuration
@EnableWebMvc
@ComponentScan({"com.hello.web", "com.hello.rest"})
@Import(RestMvcConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public ViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}


@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**");
}

}
它工作正常。但现在我开始使用字符串数据REST2.4,并将其与SpringMVC集成。如何为Spring数据Rest控制器启用跨源资源共享?我试着用过滤豆来修复它

但CORS仍然是不允许的。 请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“null”。响应的HTTP状态代码为403


如何为Spring Data Rest启用CORS?

它应该适用于整个应用程序。请参阅[this][1]SO线程。您应该注册过滤器bean。[1] :我看到了它,并注册了一个过滤器bean,但它没有运行。这就是我问自己问题的原因。据我所知,这是spring boot项目的解决方案示例。请在注册过滤器的位置添加配置,因为我已将配置文件添加到此问题中。
@Configuration
public class RestMvcConfig extends RepositoryRestMvcConfiguration {

@Override
public RepositoryRestConfiguration config() {
    RepositoryRestConfiguration config = super.config();
    config.setBasePath("/api");
    config.setDefaultMediaType(new MediaType("application", "json", Charset.forName("utf-8")));
    return config;
}

@Bean
public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true); // you USUALLY want this
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
}