5
votes

I'm not able to get the custom response header in interceptor when i console log it. console logged the interceptor httpResponse

''Console log response''

HttpResponse { headers: HttpHeaders, status: 200, statusText: "OK", ok: true, … }

HttpHeaders lazyInit : ƒ () lazyUpdate : null normalizedNames : Map(0) {} proto : Object ok : true status : 200 statusText : "OK" type : 4

We also added the Access-control-expose-header in the server side. Still i'm not getting the response. Not sure whether i miss something in the interceptor method.

Interceptor method

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                'Accept': 'application/vnd.employee.tonguestun.com; version=1',
                'Content-Type': 'application/json',
            }
        });

    return next.handle(req)
        .do((ev: HttpEvent<any>) => {
            console.log(ev)
            if (ev instanceof HttpResponse) {
                console.log(ev.headers);
            }
            // return ev;
        })

}

interceptor fuction

Custom header in network tab

access-control-allow-credentials: true

access-control-allow-methods: GET, POST, OPTIONS

access-control-allow-origin: *

access-control-expose-headers: access-token,client,expiry,token-type,uid

access-token: haIXZmNWSdKJqN2by7JH1g

cache-control: max-age=0, private, must-revalidate

client: j_2dxD7NVMjGeX8BbBuELA

content-type: application/json; charset=utf-8

expiry: 1525931943

getting custom headers in network tab

Also this is my service call, added observe 'response' in the call too.

Service call

return this.http.post(`${environment.baseUrl}${environment.signup}`, data, {observe: "response"})
  .map(response => response);

service call

AppModule.ts

import { BrowserModule } from '@angular/platform-browser';
   import { NgModule } from '@angular/core';
   import { CommonModule } from '@angular/common';

   import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppInterceptor } from './services/app-interceptor.service';

import { HomeModule } from './home/home.module'; 
import { SharedModule } from './shared/shared.module';
import { AppRoutingModule } from './app-routing.module';
import { AuthService } from './services/auth.service';
import { AuthGuardService } from './services/auth-guard.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    CommonModule,
    HttpClientModule,
    BrowserAnimationsModule,
    HomeModule,
    SharedModule,
    AppRoutingModule,
  ],
  providers: [
    AuthService,
    AuthGuardService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AppInterceptor,
      multi: true
    },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Help me please. Thanks in advance!

4
Post code as text, not images.sabithpocker

4 Answers

1
votes

This implementation of HttpInterceptor should be of help to you. The HttpResponse class has a Headers property which will help you read your response header.

0
votes

Same problem i have faced. If you call your service via http it will not work, because interceptor not familiar with it please use httpClient then automatically interceptor detect your each request, and interceptor also send your headers to server side

AppHttpInterceptor.ts

    import { Injectable } from "@angular/core";
    import {
        HttpInterceptor,
        HttpRequest,
        HttpResponse,
        HttpErrorResponse,
        HttpHandler,
        HttpEvent
    } from '@angular/common/http';

    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/do';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';
    import { Http, Response, RequestOptions, Headers } from '@angular/http';
    import { Router } from '@angular/router'


    @Injectable()
    export class AppHttpInterceptor implements HttpInterceptor {
        constructor(private router: Router){

        }
        headers = new Headers({
            'Content-Type': 'application/json',
            'Token': localStorage.getItem("Token")
        });
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

            console.log("intercepted request ... ");

            // Clone the request to add the new header.
            const authReq = req.clone({ headers: req.headers.set("Token", localStorage.getItem("Token")) });

            console.log("Sending request with new header now ...");

            //send the newly created request
            return next.handle(authReq)
                .catch(err => {
                    // onError
                    console.log(err);
                    if (err instanceof HttpErrorResponse) {
                        console.log(err.status);
                        console.log(err.statusText);
                        if (err.status === 401) {
                            window.location.href = "/login";
                        }
                    }
                    return Observable.throw(err);
                }) as any;
        }
    }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClient } from "@angular/common/http";
import { FormsModule } from '@angular/forms';
import { ToasterModule, ToasterService } from "angular2-toaster";
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import {AppHttpInterceptor} from './Common/AuthInterceptor';
import { AppRoutes } from '../app/Common/Routes';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule, HttpModule,HttpClientModule, ReactiveFormsModule, FormsModule, BrowserAnimationsModule, RouterModule.forRoot(AppRoutes)
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AppHttpInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { 
  constructor(private httpClient: HttpClient){
    this.httpClient.get("https://jsonplaceholder.typicode.com/users").subscribe(
      success => {
        console.log("Successfully Completed");
        console.log(success);
      }
    );
  }
}
0
votes

This Stack Overflow answer helped us solve this issue. The problem is in the nginx configuration. We missed always keyword in access-control-expose-header.

-1
votes

from the docs https://angular.io/guide/http#intercepting-requests-and-responses

const authReq = req.clone({
      headers: req.headers.set('Authorization', authToken)
    });

    // send cloned request with header to the next handler.
    return next.handle(authReq);

see that use a new variable, see how change the headers using set over req.headers