3

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();  }));
    }

}
3
  • Have you exposed the custom headers from server using access-control-expose-headers? because not all headers are allowed to be accessed from the client side Commented Jun 5, 2020 at 4:04
  • Yes, this was in indeed the reason. Thanks! Commented Jun 5, 2020 at 4:38
  • I added more info in the answer for future readers Commented Jun 5, 2020 at 11:20

2 Answers 2

2

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' '*';
Sign up to request clarification or add additional context in comments.

Comments

2

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); 
            });
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.