0

I tried setting up an Angular Interceptor where every request must have all the necessary HTTP headers and tokens before the API Call takes place. Earlier I used to do this in every Service, but now I am trying with HTTP Interceptors, which sets the Headers with every HTTP Request.

However, upon checking the browser, I dont find the headers being sent from the app. Here is my code:-

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

@Injectable()
export class MasterAPIInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    //const headers= new HttpHeaders();
    const userToken = 'secure-user-token';
      req.headers.set('content-type', 'application/json')
      .set('Access-Control-Allow-Origin', '*');
      req.headers.set('Authorization', `Bearer ${userToken}`)
     const headerReq = req.clone({ headers: req.headers });

    return next.handle(headerReq);
  }
}


Where am I going wrong?

Also, is there any clearer way to check if the headers are set properly?

Asish
  • 760
  • 1
  • 10
  • 16

1 Answers1

1

The reason is that HttpHeaders.set returns a new object. So you need to store a reference to this new object into a some variable. In you code you don't do this.

See the detailed answer here https://stackoverflow.com/a/49768617/12488082

AlexElin
  • 1,044
  • 14
  • 23