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:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
});
console.log('Intercepted HTTP call', authReq);
return next.handle(authReq);
}
}
Apart of the 'Content-Type'
header I need to add an 'Authorization'
but I don't how to do it (the documentation of Angular HttpHeaders is just the list of the methods, without any explanation).
How can I do it? Thanks!
@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);
}
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')
});
As mentioned before - accepted method overrides headers, for adding them I like approach from API documentation:
const authReq = req.clone({ setHeaders: { Authorization: authToken } });
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.
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
来源:https://stackoverflow.com/questions/48683476/how-to-add-multiple-headers-in-angular-5-httpinterceptor