【发布时间】:2020-06-06 00:40:43
【问题描述】:
我必须在每个 HTTP 请求的“授权”标头中放置一个令牌。 所以我开发并注册了一个 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();
}
}));
}
}
但标题似乎永远不会放在发送的请求上。我做错了什么?
此外,有时错误代码“0”会被拦截器捕获;什么意思?
Angular 8.2.11
编辑 1:------------
我也试过这样:
request = request.clone({
setHeaders: {
authorization: `Bearer ${token}`
}
});
但仍然没有设置标题。 此外,该模块已在 app.module 中正确注册
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor ,
multi: true,
}..
编辑 2:------------
查看这张图片...我快疯了。
【问题讨论】:
标签: javascript angular typescript angular-http-interceptors