Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access headers from a HttpClient response? (Angular / Ionic)

I'm using a login endpoint that returns a bearer token as a response header, as I can see in the "Network" Chrome inspect window:

Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8100
Authorization:Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuZWxpby5jdXJzb3NAZ21haWwuY29tIiwiZXhwIjoxNTEyNzA3OTQ3fQ.pOR4WrqkaFXdwbeod1tNlDniFZXTeMXzKz9uU68rLXEWDAVRgWIphvx5F_VCsXDwimD8Q04JrxelkNgZMzBgXA
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:188
(etc...)

However, when I try to print "headers" from the response using a HttpClient instance:

  authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({"Content-Type": "application/json"});
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response'})
      .subscribe(
        (resp) => {
          console.log("resp-ok");
          console.log(resp.headers);
        },
        (resp) => {
          console.log("resp-error");
          console.log(resp);
        }
      );
  }

I get a completely different structure:

HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}

I also tried the get(headerName) method and got null. What am I missing? How can I get that "Authorization" header from my response?

like image 755
Nelio Alves Avatar asked Dec 07 '17 04:12

Nelio Alves


Video Answer


1 Answers

try like this :

authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({ "Content-Type": "application/json" });
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response' })
        .subscribe(
        (resp) => {
            let header: HttpHeaders = resp.headers;
            console.log(header.get('Authorization'))
        },
        (resp) => {
            console.log("resp-error");
            console.log(resp);
        }
        );
}
like image 134
Chandru Avatar answered Oct 02 '22 01:10

Chandru