gpt4 book ai didi

spring - 在 Spring 上启用 CORS 访问 MongoDB 数据

转载 作者:行者123 更新时间:2023-12-03 00:18:35 25 4
gpt4 key购买 nike

我正在尝试使用 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 beans),它可能类似于:

@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);
}
}

关于spring - 在 Spring 上启用 CORS 访问 MongoDB 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com