Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read response headers from API response - Angular 5 + TypeScript

I'm triggering a HTTP request and I'm getting a valid response from it. The response also has a header X-Token that I wish to read. I'm trying the below code to read the headers, however, I get null as a result

this.currentlyExecuting.request = this.http.request(reqParams.type, reqParams.url, {     body: reqParams.body,     responseType: 'json',     observe: 'response' }).subscribe(     (_response: any) => {         // Also tried _response.headers.init();         const header = _response.headers.get('X-Token');         console.log(header);         onComplete(_response.body);      },     _error => {         onComplete({             code: -1,             message: Constants.WEBSERVICE_INTERNET_NOT_CONNNECTED         });     } ); 

The response of the API, when checked in Chrome inspect, shows the header is present.

enter image description here

like image 832
Sahil Khanna Avatar asked Jan 10 '18 09:01

Sahil Khanna


1 Answers

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'));   }); 
like image 168
Hrishikesh Kale Avatar answered Sep 21 '22 17:09

Hrishikesh Kale