3

I'm trying to develop a RestFul Web Service with Spring, that fetches data from a mongoDB collection and serves it to a client. To build the service i followed this guide on spring.io. Everything went well, i can access data from mongoDB and search it for the data structure name. The troubles began when i tried to manage requests from my client, i receive classical error of same-domain-policy violation.

No 'Access-Control-Allow-Origin' header is present on the requested resource.

The project is EXTREMELY simple, is composed of those 3 classes:

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

}

I tried different methods found in the documentation See here but without results...

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
formich
  • 33
  • 4

2 Answers2

2

A similar question is Spring Data Rest and Cors

The answer is that if you are using Spring Boot (which supports Filter beans), it could be something like:

@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);
    }
}
Community
  • 1
  • 1
gioelem3
  • 48
  • 1
  • 5
0

have you tried to add a class like this?

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

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

it worked for me

UKoehler
  • 131
  • 7