Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access response headers using HttpClient in Angular 5?

I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. The backend responds by sending a JWT bearer token.

My request looks like this:

return this.http.post('http://127.0.0.1:8080/api/v1/login', {
  'username': username,
  'password': password
}, {
  headers: new HttpHeaders()
    .set('Content-Type', 'application/json')
})
  .toPromise()
  .then(response => {
    console.log(response);
    return response;
  });

}

How do I access the authorization header of the response?

When I write the response to the console, like above, it says 'null'. I know the error is not in the backend because I captured the traffic and the backend is indeed sending the bearer token.

Any help is very much appreciated.

like image 759
Florian Avatar asked Dec 11 '17 13:12

Florian


People also ask

How do I view HTTP response headers?

To view the request or response HTTP headers in Google Chrome, take the following steps : In Chrome, visit a URL, right click , select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.

How can you read full response in Angular?

You can obtain the full response using the observe property and specifying the response value. This way Angular will hand you the full HttpResponse object. Let's see this with an example. We simply import HttpClient from the @angular/common/http package and inject is as httpClient via the service constructor.

How do I add HTTP response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

What is HTTP headers in Angular?

HTTP Headers let the client and the server share additional information about the HTTP request or response. For example, we use the content-type header to indicate the media type of the resource like JSON, text, blob, etc.


1 Answers

To access the full response (not just the body of the response), you must pass the observe: 'response' parameter option in your http request. Now you can access the headers with res.headers

return this.http.post('http://127.0.0.1:8080/api/v1/login', {
        'username': username,
        'password': password
    }, {
        headers: new HttpHeaders()
            .set('Content-Type', 'application/json'),
        observe: 'response'
    })
    .map(res => {
        let myHeader = res.headers.get('my-header');
    });

Docs

like image 125
LLai Avatar answered Oct 22 '22 15:10

LLai