我试图学习如何使用HttpInterceptor为应用程序对API执行的每个HTTP请求添加几个标头。我有这个拦截器:
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);
}
}
除了内容类型&#39;标题我需要添加一个&#39;授权&#39;但我不知道怎么做(Angular HttpHeaders的文档只是方法列表,没有任何解释)。
我该怎么办?谢谢!
答案 0 :(得分:19)
@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);
}
答案 1 :(得分:12)
由于set
方法每次都返回头对象,因此您可以执行此操作。这样,来自截获的请求的原始标题也将被保留。
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
.set('header2', 'header 2 value')
.set('header3', 'header 3 value')
});
答案 2 :(得分:4)
如前所述-接受的方法会覆盖标头,要添加标头,我喜欢从API documentation中获取方法:
const authReq = req.clone({ setHeaders: { Authorization: authToken } });
答案 3 :(得分:3)
const modifiedReq = req.clone({
url: this.setUrl(req.url),
headers: this.addExtraHeaders(req.headers)
});
方法:
private addExtraHeaders(headers: HttpHeaders): HttpHeaders {
headers = headers.append('myHeader', 'abcd');
return headers;
}
方法.append创建一个新的HttpHeaders对象,添加myHeader并返回新对象。
使用此解决方案意味着您还可以使用多个拦截器,因为您不会覆盖标头。
答案 4 :(得分:1)
以上解决方案就像魅力一样。记住要在第2行的头中分配追加回叫!
ng serve
答案 5 :(得分:0)
在拦截器文件中
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]
})
答案 6 :(得分:-1)
我尝试过使用拦截器发送自定义标头的方法。请查看链接stackBlitz
请参阅控制台屏幕截图以获取参考browser console-request header
自定义标题已添加到
中的访问控制请求报头:AUTHKEY,内容类型,设备ID
我希望将标头添加为标头的一部分,而不是在access-control-request-headers内。请在此建议我