Intercepting HTTP response headers with Angular 4.3 HttpInterceptor
This is how I send my HTTP request:
return this.http.get(url, { observe: 'response' })
I would like to read the HttpResponse HTTP headers in my HttpInterceptor:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.do(event => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event); // Headers are missing here
}
})
.catch((err: HttpErrorResponse) => {
// Do stuff
}
}
The interceptor is presented as in my .module.ts application:
{provide: HTTP_INTERCEPTORS, useClass: MyHttpInterceptor, multi: true}
The event doesn't seem to have headers , and even in the Chrome Dev console I can't see the headers:
However, when using Postman, I can see the headers in the response (as expected)
Connection →keep-alive
Content-Length →14766
Content-Type →application/json
Date →Fri, 04 Aug 2017 14:50:46 GMT
Server →WildFly/10
X-Powered-By →Undertow/1
How can I expand these headers in Angular?
The official docs for HTTP says to get headers like this:
http
.get<MyJsonData>('/data.json', {observe: 'response'})
.subscribe(resp => {
// Here, resp is of type HttpResponse<MyJsonData>.
// You can inspect its headers:
console.log(resp.headers.get('X-Custom-Header'));
// And access the body directly, which is typed as MyJsonData as requested.
console.log(resp.body.someField);
});
source to share
I found the answer. This was (of course) a CORS problem. I am using CORS Filter and I needed to explicitly expose my custom header. I hope this can help others eventually.
source to share
Similar to server side CORS filter configuration.
By default, only 6 simple response headers are displayed:
- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
If you want clients to access other headers, you must list them using the Access-Control-Expose-Headers header.
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
source to share
To view the headings, enter the "headings" in the response. The headers are lazy evaluated so they are not visible. I suppose headers are only evaluated when you explicitly request them with resp.headers.get
. However, you can get a list of headers in the response with res.headers.keys()
. For example.
yourFunction.subscribe((res:HttpResponse<any>)=>{console.log('response from server:',res);
console.log('response headers',res.headers.keys())
} );
source to share
It is not related to Angular. The problem is that CORS restricts headers by default and you don't see the "X-Custom-Header" header when making CORS requests. So, configure your server to send the X-Custom-Header.
Access-Control-Allow-Headers must be provided in response to an OPTIONS (pre-flight) request.
Access-Control-Expose-Headers must be provided in response to a POST / GET request.
Access-Control-Expose-Headers: X-Custom-Header
source to share