Read response headers from API response - Angular 5 + TypeScript
Have you exposed the X-Token
from server side using access-control-expose-headers
? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side
Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'}
like
http .get<any>('url', {observe: 'response'}) .subscribe(resp => { console.log(resp.headers.get('X-Token')); });
In my case in the POST
response I want to have the authorization header
because I was having the JWT Token
in it.So what I read from this post is the header I we want should be added as an Expose Header
from the back-end.So what I did was added the Authorization
header to my Exposed Header like this in my filter class
.
response.addHeader("Access-Control-Expose-Headers", "Authorization");response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, X-Custom-header");response.addHeader(HEADER_STRING, TOKEN_PREFIX + token); // HEADER_STRING == Authorization
And at my Angular Side
In the Component.
this.authenticationService.login(this.f.email.value, this.f.password.value) .pipe(first()) .subscribe( (data: HttpResponse<any>) => { console.log(data.headers.get('authorization')); }, error => { this.loading = false; });
At my Service Side.
return this.http.post<any>(Constants.BASE_URL + 'login', {username: username, password: password}, {observe: 'response' as 'body'}) .pipe(map(user => { return user; }));
You should use the new HttpClient
. You can find more information here.
http .get<any>('url', {observe: 'response'}) .subscribe(resp => { console.log(resp.headers.get('X-Token')); });