Doubt with the use of angular interceptor

0

My question is this using the angular interceptor to send the token in each request to my back-end I see that it makes two requests one without adding the token and another with the token, my question is this is normal since my response effectively returns only one but when I check my console I see that it makes two requests, this Is it because of the angular clone? can this affect performance?

  

Code of my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AuthInterceptorService } from './services/auth.interceptor.service';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './modules/router.module';

import { PrincipalComponent } from './components/principal/principal.component';
import { NotFoundComponent } from './components/errors/not.found.component';
import { LoginComponent } from './components/auth/login.component';


@NgModule({
  declarations: [
    AppComponent,
    PrincipalComponent,
    NotFoundComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptorService,
      multi: true
    }],
  bootstrap: [AppComponent]
})
export class AppModule { }
  

auth.interceptor.service.ts

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const request = req.clone({
            setHeaders: {
                Authorization: 'Bearer ${localStorage.getItem('token')}'
            }
        });

        return next.handle(request);
    }
}
    
asked by Ronny Medina 21.01.2018 в 17:44
source

1 answer

0

The first request is with the OPTIONS method to verify that the resource you want to request is available, Angular does it by default for you.

HTTP Source Methods

The second request is yours once Angular has verified that the requested resources are available.

    
answered by 21.01.2018 в 18:09