Haytham Dahri
Haytham Dahri

Reputation: 13

HttpInterceptor not working for all requests

I am using the new version of angular and i am facing the issue of not sending authorization token within the request header for all some requests. I checked everything and still the same problem since i upgraded to the new version 8. When i send some requests, i couldn't find the authorization header even if i printed it in the console to check its presence.

This is the new version of Angular 8.

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

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(
    req: HttpRequest,
    next: HttpHandler
  ): Observable> {
    // Retrieve logged in user if connected
    const userToken = this.authService.getAuthenticatedUser();
    // Verify existing of the user
    if (userToken != null && userToken.bearerToken != null) {
      req = req.clone({
        setHeaders: {
          Authorization: userToken.bearerToken
        }
      });
    }
    return next.handle(req);
  }
}

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    FooterComponent,
    HomeComponent,
    ContactUsComponent,
    NotFoundComponent,
    CartComponent,
    LoginComponent
  ],
  imports: [BrowserModule, AppRoutingModule, CustomModule, LayoutModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

I was expecting to have the authorization header.

Upvotes: 0

Views: 1684

Answers (1)

Chaitanya
Chaitanya

Reputation: 939

Import HTTP_INTERCEPTORS and your service and provide them in providers

<! app.module.ts -->
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { RequestInterceptor } from './your-interceptor-path'

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    }
  ]

You're cloning only Authorization header into the HttpRequest

Add following lines into your RequestInterceptor service next to Authorization header clone

if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

req = req.clone({ headers: req.headers.set('Accept', 'application/json') });

Upvotes: 1

Related Questions