The following code does not log custom headers from the server. Am I missing something - the only headers written out are content-type and content-length.
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { LoaderService } from './loader.service';
import { AuthService } from './services/auth-service';
import * as _ from 'lodash';
import { tap } from 'rxjs/internal/operators/tap';
@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
constructor(public loaderService: LoaderService,
private authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loaderService.show();
if (!_.isNil(this.authService.authenticatedUser) && this.authService.authenticatedUser.token) {
request = request.clone({
setHeaders: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.authService.authenticatedUser.token}`
}
});
}
return next.handle(request).pipe(tap((resp: HttpResponse<any>) => {
if (resp instanceof HttpResponse) {
for (const h of resp.headers.keys()) {
console.log('header', h);
}
}
},
(resp: any) => {
if (resp instanceof HttpErrorResponse) {
if (resp.status !== 401) {
return;
}
this.loaderService.setUnAuthorized();
}
}, () => { this.loaderService.hide(); }));
}
}
The Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names.
By default, only the 7 CORS-safelisted response headers are exposed:
Cache-Control
Content-Language
Content-Length
Content-Type
Expires
Last-Modified
Pragma
If you want clients to be able to access other headers, you have to list them using the Access-Control-Expose-Headers header.
Access-Control-Expose-Headers: *
for instance with ngnix it would be:
add_header 'Access-Control-Expose-Headers' '*';
My server implementation is in DotNet, so the following using the principle above worked:
string[] headers = new string[] {"X-Custom-1", "X-Custom-2"};
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.WithExposedHeaders(headers);
});
});
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