I\'m trying to learn how to use HttpInterceptor
to add a couple of headers to each HTTP request the app do to the API. I\'ve got this interceptor:
I have tried following ways to send custom headers using interceptors. please check the link stackBlitz
Please refer the console screenshot for your reference browser console-request header
And the custom headers are added in
access-control-request-headers:authkey,content-type,deviceid
I want the headers to be added as part of header, not inside access-control-request-headers. Please suggest me on this
const modifiedReq = req.clone({
url: this.setUrl(req.url),
headers: this.addExtraHeaders(req.headers)
});
And the method:
private addExtraHeaders(headers: HttpHeaders): HttpHeaders {
headers = headers.append('myHeader', 'abcd');
return headers;
}
The method .append creates a new HttpHeaders object adds myHeader and returns the new object.
Using this solution means that you can also use multiple interceptors because you will not overwrite your headers.
in your interceptor file
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = req.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Auth-Token': 'jwtToken'
})
});
return next.handle(auth);
}
**in app module**
import {HTTP_INTERCEPTORS} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptorService, multi: true},
],
bootstrap: [AppComponent]
})
Since the set
method returns headers object every time, you can do this. This way, original headers from the intercepted request will also be retained.
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
.set('header2', 'header 2 value')
.set('header3', 'header 3 value')
});
Edit: Following suggestions in comments I have unified both answers
Overwriting all headers
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
});
console.log('Intercepted HTTP call', authReq);
return next.handle(authReq);
}
Adding more headers without overwriting (credits to Ketan Patil - see answer in this post)
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
.set('header2', 'header 2 value')
.set('header3', 'header 3 value')
});
As mentioned before - accepted method overrides headers, for adding them I like approach from API documentation:
const authReq = req.clone({ setHeaders: { Authorization: authToken } });