Problem with Angular 2 and CROS

0

Good afternoon comapñeros,

I have a problem with Angular2 and certain POST requests when doing them from the application client.

Scenario:

  • The API is implemented in SpringBoot .

  • Client application Angular 2 + HttpClient.

  • They are in different domains (CROS) .

The request from Angular is similar to the following:

let userAccessToken = 'Bearer ' + this.storage.retrieve('UserAccessToken');  
let other = this.storage.retrieve('other');      

const headers = new HttpHeaders()
    .set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8;')
    .set('Authorization', userAccessToken)
    .set('Other', other);

this.http.post( "https://api.xxxxx.yyyy/", {}, { headers })
.subscribe(
    (val) => {
        console.log("POST call successful value returned in body", val);
    },
    response => {
        console.log("[ERROR] => POST call in error => ", response);
        console.log("[ERROR] => HEADERS => STATUS => ", response.headers.get('status'));
    },
    () => {
        console.log("The POST observable is now completed.");
    }
);

I get a response from server 200 OPTIONS which contains Access-Control-Allow-Origin: *

  Access-Control-Allow-Headers : authorization, content-type
  Access-Control-Allow-Methods : GET,POST,PUT,DELETE,OPTIONS    
  Access-Control-Allow-Origin : *
  Access-Control-Expose-Headers : xsrf-token
  Access-Control-Max-Age    : 3600
  Content-Length    : 0
  Date : Tue, 23 Jan 2018 15:18:52 GMT
  Vary : Origin

With this answer I intuit that the backend is configured correctly, however I can not realize the POST request. Why can it be?

Mucahs thank you.

    
asked by Pablo M. 23.01.2018 в 16:43
source

1 answer

1

[Solution]

When custom headers custom-headers exist, they must be explicitly enabled in the CROS configuration of the Spring-boot API

As a guideline in the Spring-boot configuration, something like:

should be added
// prepare cors config
CorsConfiguration corsConfig = new CorsConfiguration();

// Access-Control-Allow-Origin: *
corsConfig.addAllowedOrigin("*");

// Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
corsConfig.addAllowedMethod(HttpMethod.GET);
corsConfig.addAllowedMethod(HttpMethod.POST);
corsConfig.addAllowedMethod(HttpMethod.PUT);
corsConfig.addAllowedMethod(HttpMethod.DELETE);
corsConfig.addAllowedMethod(HttpMethod.OPTIONS);

// Access-Control-Max-Age: 3600
corsConfig.setMaxAge(3600L);

// Access-Control-Allow-Headers: authorization, content-type, xsrf-token
corsConfig.addAllowedHeader("authorization");
corsConfig.addAllowedHeader("content-type");
corsConfig.addAllowedHeader("custom-header");
corsConfig.addAllowedHeader("other");

Greetings

    
answered by 24.01.2018 в 15:15