Joe
Joe

Reputation: 385

Angular 5 response header is missing on CORS

In my angular app, I need to retrieve Location data from the response header. The server (Nginx) is configured to allow cross origin and to allow/expose location in header. I can see this in the chrome DEV console but in my angular app, I don't see any data for the header.

Access-Control-Allow-Origin: *
Access-Control-Allow-Headers:Location, Content-Type
Access-Control-Expose-Headers:Location, Content-Type

Here is my code snippet.

this.httpClient.post( url, {
        UserName: username,
        Password: password
      }
    )
      .subscribe(
        (res: Response) => {
          console.log(res.headers);
        },
        error => {console.log('Error occured::' + error);
        }
      );

console.log(res.headers) returns undefined.

What's going wrong here?

Upvotes: 2

Views: 2667

Answers (2)

Joe
Joe

Reputation: 385

OK. There were two issues. As @Manduro pointed out, need to add observe in the angular request. Another one is I missed the comma between two header types.

https://enable-cors.org/server_nginx.html

Need to add 'always' keyword in the location config file

Upvotes: 0

Manduro
Manduro

Reputation: 843

The new HttpClient returns only the body by default. Should you want to retrieve anything from the response itself you can use the option observe:

  this.httpClient.post(url, {
    UserName: username,
    Password: password
  }, {
    observe: 'response'
  })
  .subscribe(res => {
    console.log(res.headers.get('Location');
  }, error => {
    console.log('Error occured::' + error);
  });

You were typecasting res to Response so TypeScript didn’t catch your error. It’s better to remove the type as in my example so it is automatically typed correctly.

Upvotes: 3

Related Questions