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?