0

I have a problem with get request in Angular 2. I have a method to get documents:

getDocuments() {
   let username: string = 'username';
   let password: string = 'password';
   let headers: Headers = new Headers();
   headers.append("Authorization", "Basic " + btoa(username + ":" + password));
   headers.append("Content-Type", "multipart/form-data");
   return this._http.get('http://localhost:8080/api/documents', {headers: headers}).map(res => res.json());
}

And there is an error:

Response for preflight is invalid (redirect)

Solution, it worked for me (added in SpringBoot app):

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    org.springframework.web.cors.CorsConfiguration config = new org.springframework.web.cors.CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://localhost:4200");
    config.setAllowedMethods(Arrays.asList("POST", "OPTIONS", "GET", "DELETE", "PUT"));
    config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}
Helosze
  • 333
  • 2
  • 7
  • 20
  • 3
    You need to configure the server to allow CORS. – Günter Zöchbauer Sep 13 '17 at 09:13
  • I've done it (added @CrossOrigin(origins = "http://localhost:4200") in SpringBoot) and it still doesn't work. – Helosze Sep 13 '17 at 09:37
  • 1
    I don't know about your server. I know this is not related to Angular. There are probably other configuration options missing. – Günter Zöchbauer Sep 13 '17 at 09:46
  • 1
    Take a look at [this](https://stackoverflow.com/questions/34949492/cors-request-with-preflight-and-redirect-disallowed-workarounds/39728229#39728229) and [this](https://stackoverflow.com/questions/42168773/how-to-resolve-preflight-is-invalid-redirect-in-cors) – Surender Khairwa Sep 13 '17 at 10:01
  • 1
    HI we have repo demo https://github.com/RobertRajcool/Angular2-Spring-Mvc – Robert Sep 13 '17 at 10:15
  • 1
    @GünterZöchbauer you were right, I needed some CORS filter on my server. Surender&Robert, thanks, but I've resolved the problem already. :) – Helosze Sep 13 '17 at 10:37
  • How do you manage to solve this without CORS filter on server? – Samir May 31 '18 at 11:48

1 Answers1

0

This question is about getting a REST response, but the server returns a redirect. This does not match.

I did some tests with Angular/SpringBoot/Oauth2 in this area, so, that's why I could reply this exact situation.

tm1701
  • 7,307
  • 17
  • 79
  • 168