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.
As Hrishikesh Kale has explained we need to pass the Access-Control-Expose-Headers.
Here how we can do it in the WebAPI/MVC environment:
Another way is we can add code as below in the webApiconfig.cs file.
**We can add custom headers in the web.config file as below. *
we can create an attribute and decore the method with the attribute.
Happy Coding !!
Have you exposed the
X-Token
from server side usingaccess-control-expose-headers
? because not all headers are allowed to be accessed from the client side, you need to expose them from the server sideAlso in your frontend, you can use new HTTP module to get a full response using
{observe: 'response'}
likeIn my case in the
POST
response I want to have theauthorization header
because I was having theJWT Token
in it. So what I read from this post is the header I we want should be added as anExpose Header
from the back-end. So what I did was added theAuthorization
header to my Exposed Header like this in myfilter class
.And at my Angular Side
In the Component.
At my Service Side.
You can get headers using below code
later we can get the required header form the json object.
You should use the new
HttpClient
. You can find more information here.Angular 7 Service:
Component: