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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With