1

According to the spring boot documentation I added bean

 @Bean
WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:3000");
        }
    };
}

to enable global access from localhost:3000 , which is my frontend app. I also use spring security, so if user enter localhost:8080/something he is redirected to login page ( if not logged ) . The problem is that this global cors configuration doesn't work.

I have simple controller which returns

List<String> 

On the other hand I have angular service, which is responsible for making a get request to the server. It looks like this :

  this.http.get("http://localhost:8080/words", {
            headers: new Headers({
                'Authorization': 'Basic ' + btoa('login:password')
            })
        }).map((res:Response) => res.json())
        .subscribe(
            data => { this.words = data},
            err => console.error('Error :  ' + err),
            () => console.log('done')
        );

and as a result I can see in google chrome console :

 XMLHttpRequest cannot load http://localhost:8080/words. Response for preflight is invalid (redirect)

How can I fix this ?

Pande
  • 27
  • 2
  • 1
    How about searching in Google with that error message? – Eric Martinez Mar 26 '16 at 16:20
  • I think the problem is: http://stackoverflow.com/questions/17496452/how-to-follow-a-redirect-in-http-get-in-angularjs http://stackoverflow.com/questions/29469249/handle-redirects-in-angularjs-http Hope these can help you. – Sola Mar 26 '16 at 16:27
  • 1
    Could you provide the response content (headers) of the OPTIONS request? Thanks! – Thierry Templier Mar 26 '16 at 18:50

1 Answers1

0

This is because your front end application makes an OPTIONS HTTP before actual data transfer happens. Try adding this configuration to your spring project:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

  @Value("${angular}")
  private String angularOrigin;

  @Bean
  public WebMvcConfigurer corsConfigurer(){
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry
            .addMapping("/**")
            .allowedOrigins(angularOrigin)
            .allowedHeaders("Authorization", "Cache-Control", "Content-Type", "Accept", "X-Requested-With", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin")
            .exposedHeaders("Access-Control-Expose-Headers", "Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin")
            .allowedMethods("PUT","GET","POST","DELETE","OPTIONS");
      }
    };
  }
}
Alisher
  • 480
  • 5
  • 16