[英]Angular HTTP interceptor for Authentication header
I have to put a token inside the 'Authorization' header for every HTTP request.我必须在每个 HTTP 请求的“授权”标头中放置一个令牌。 So I have developed and registered an HttpInterceptor :所以我开发并注册了一个 HttpInterceptor :
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public authService: AuthService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let modifiedReq;
const token = this.authService.getToken();
// we need the heck clone because the HttpRequest is immutable
// https://angular.io/guide/http#immutability
if (token) {
modifiedReq = request.clone();
modifiedReq.headers.set('Authorization', `Bearer ${token}`);
}
return next.handle(modifiedReq ? modifiedReq : request).pipe(tap(() => {
// do nothing
},
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 0) {
alert('what the heck, 0 HTTP code?');
}
if (err.status !== 401) {
return;
}
this.authService.goToLogin();
}
}));
}
}
But the header seems never to be put on the request sent.但是标题似乎永远不会放在发送的请求上。 What am I doing wrong?我究竟做错了什么?
Also, sometimes an errorcode '0' gets caught by the interceptor;此外,有时拦截器会捕获错误代码“0”; what does it mean?这是什么意思?
Angular 8.2.11角 8.2.11
EDIT 1: ------------------------编辑1:------------------------
I've also tried like this:我也试过这样:
request = request.clone({
setHeaders: {
authorization: `Bearer ${token}`
}
});
but still no header has been set.但仍然没有设置标题。 Also, the module is correctly registered in app.module此外,该模块已在 app.module 中正确注册
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor ,
multi: true,
}..
EDIT 2 : ------------------------编辑 2:------------------------
Check this image... I'm going crazy.检查这张图片...我快疯了。
maybe you forget to put in app.module
this:也许你忘了把app.module
这个:
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor ,
multi: true,
}..
the final part write in this way:最后一部分是这样写的:
return next.handle(modifiedReq);
It's working for me like this:它对我来说是这样的:
const headersConfig = {
'Accept': 'application/json', //default headers
};
...
if (token) {
headersConfig['Authorization'] = `Bearer ${token}`;
}
...
return next
.handle(request.clone({
setHeaders: headersConfig
}))
I was wrong.我错了。 When doing update of the clone request, angular will put the new headers in fields called " lazyUpdate " and not direcly inside the headers.在更新克隆请求时,angular 会将新的标头放在名为“ lazyUpdate ”的字段中,而不是直接放在标头中。 The requests were failing because of other reasons.由于其他原因,请求失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.