【问题标题】:Enable CORS On Spring accessing MongoDB data在 Spring 上启用 CORS 访问 MongoDB 数据
【发布时间】:2016-07-18 04:34:10
【问题描述】:

我正在尝试使用 Spring 开发一个 RestFul Web 服务,它从 mongoDB 集合中获取数据并将其提供给客户端。为了构建服务,我关注了this guide on spring.io。一切顺利,我可以从 mongoDB 访问数据并搜索数据结构名称。 当我尝试管理来自客户的请求时,麻烦就开始了,我收到了相同域策略违规的经典错误。

请求中没有“Access-Control-Allow-Origin”标头 资源。

这个项目非常简单,由这 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 cors


    【解决方案1】:

    类似的问题是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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      你试过添加这样的类吗?

      @Configuration
      @EnableWebMvc
      public class WebConfig extends WebMvcConfigurerAdapter {
      
          @Override
          public void addCorsMappings(CorsRegistry registry) {
              registry.addMapping("/**");
          }
      }
      

      对我有用

      【讨论】:

      • 我刚试过,但它不起作用,总是给我同样的错误
      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 2016-10-31
      • 2020-02-20
      • 2015-10-16
      • 2021-03-15
      • 2014-03-06
      • 2019-10-05
      • 2018-04-09
      相关资源
      最近更新 更多