我正在使用Spring 4.2.1版本开发Spring(非Boot)应用程序。我在Web配置文件中为Spring MVC启用了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("/**");
}
}
它工作正常。但现在我开始使用String Data Rest 2.4并将其与Spring MVC集成。如何为Spring Data Rest控制器启用跨源资源共享?我尝试使用过滤器bean Spring Data Rest and Cors
修复它@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);
}
}
但仍然不允许使用CORS。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' null'因此不允许访问。响应的HTTP状态代码为403。
如何为Spring Data Rest启用CORS?