我正在尝试使用
Spring开发RestFul Web服务,该服务从mongoDB集合中获取数据并将其提供给客户端.为了构建我遵循
this guide on spring.io的服务.一切顺利,我可以从mongoDB访问数据并搜索它的数据结构名称.
当我试图管理来自我的客户端的请求时,麻烦就开始了,我收到了相同域策略违规的经典错误.
No ‘Access-Control-Allow-Origin’ header is present on the requested
resource.
该项目非常简单,由以下3个类组成:
Frames.java
@Id
private String Id;
private String frameName;
private ArrayList<String> frameElements;
public String getId() {
return Id;
}
public String getFrameName() {
return frameName;
}
public ArrayList<String> getFrameElements() {
return frameElements;
}
FrameRestFulServiceApplication.java
@SpringBootApplication
public class FrameRestFulServiceApplication {
public static void main(String[] args) {
SpringApplication.run(FrameRestFulServiceApplication.class, args);
}
}
FramesRepository.java
@RepositoryRestResource(collectionResourceRel = "frames", path = "frames")
public interface FramesRepository extends MongoRepository<Frames, String>{
List<Frames> findByFrameNameLike(@Param("frameName") String frameName);
List<Frames> findByFrameName(@Param("frameName") String frameName);
}
我尝试了文档See here中找到的不同方法但没有结果……
最佳答案 一个类似的问题是
Spring Data Rest and Cors
答案是,如果您使用的是Spring Boot(支持Filter bean),它可能是这样的:
@Configuration
public class RestConfiguration {
@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);
}
}