Victor Bredihin
Victor Bredihin

Reputation: 2360

angular4 interceptor causes duplicated http requests

Here is my interceptor

// src/app/auth/token.interceptor.ts
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpErrorResponse,
  HttpInterceptor
} from '@angular/common/http';
import { JwtService } from '@app/services/jwt.service';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor(public jwtService: JwtService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const headersConfig = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };

    if (this.jwtService.getToken()) {
      headersConfig['Authorization'] = `Bearer ${this.jwtService.getToken()}`;
    }

    request = request.clone({
      setHeaders: headersConfig
    });
    return next.handle(request).do((event: HttpEvent<any>) => {

    }, (err: any) => {

    });
  }
}

and my app.module, everything like in documentation

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    SidebarComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes
      , { preloadingStrategy: PreloadAllModules }
    ),
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MyInterceptor,
      multi: true
    },
    JwtService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

This causes duplicated http requestsenter image description here

I found that when I remove setHeaders option, the problem is fixed, but I created intercepter to add authorization header in the first place. Please help me to understand what's wrong

Upvotes: 3

Views: 2825

Answers (1)

Hugo Noro
Hugo Noro

Reputation: 3243

When you have an authenticated request initially there is one request of the type OPTIONS that is done during the called preflight. It’s a kind of handshake with the server figuring out if it accepts requests of that type. If all goes OK it will then do the actual GET, POST, etc. request you initially did. I believe that’s what you’re experiencing.

Edit

Your problem might reside in the way you are setting the headers.

Try the following

request = request.clone({
      headers: headersConfig
    });

Upvotes: 3

Related Questions