3

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

5
  • what's weird, it's call first http (the call initialized by zonejs), waits until it's done and then call the second one Commented Nov 30, 2017 at 22:54
  • 1
    these are not duplicate requests, the first is a preflight options request validating that you are authorized to make requests on this domain, it's happening because you're adding auth headers, this is standard browser behavior. Commented Nov 30, 2017 at 23:00
  • @bryan60 so, it is the correct behavior that I see 2 http requests, when add any header? in my example I don't have auth header, cause there is no jwt token Commented Nov 30, 2017 at 23:28
  • yea pretty much any header alteration will trigger a pre flight request, it causes no performance issues whatsoever, and happens in every browser. Most of the time the request is actually browser cached. Commented Dec 1, 2017 at 0:56
  • @bryan60 thank you, so I thing I do nothing wrong. But I'm working not the first year, and never seen this behavior before. I would say it's not so usual behavior, since before I start using interceptor there was no these OPTIONS requests Commented Dec 1, 2017 at 9:50

1 Answer 1

3

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

9 Comments

so, it is the correct behavior that I see 2 http requests, when add any header? in my example I don't have auth header, cause there is no jwt token
My edit was based on this source. Have a look and see if you can spot something you’re doing differently juristr.com/blog/2017/08/intercept-http-requests-in-angular
yea, I checked this one and many other links before asking. I'm more interested in you original answer, can u give me some link about this behavior? You said it's ok, but for me it looks like 2 requests need more time then without interceptor, before that I was using custom apiService instead of interceptor for the same goal, and there was no this problem. So, I kind of doubt that this duplicated request is fine
Can you check the type of request? I’m suspecting one of them is of the type HEAD and the other of the type GET or POST or whatever was the original type.
one of them with type 'OPTIONS'
|

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.