Javascript 用于身份验证头的角度HTTP侦听器
对于每个HTTP请求,我必须在“授权”头中放置一个令牌。 因此,我开发并注册了一个HttpInterceptor:Javascript 用于身份验证头的角度HTTP侦听器,javascript,angular,typescript,angular-http-interceptors,Javascript,Angular,Typescript,Angular Http Interceptors,对于每个HTTP请求,我必须在“授权”头中放置一个令牌。 因此,我开发并注册了一个HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public authService: AuthService) { } intercept(request: HttpRequest<any>, next: HttpHandler
@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();
}
}));
}
}
但仍然没有设置标题。
此外,模块已在app.module中正确注册
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor ,
multi: true,
}..
编辑2:---------------------------
检查此图像。。。我快疯了。也许你忘了在
应用程序模块中输入以下内容:
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor ,
multi: true,
}..
最后一部分是这样写的:
return next.handle(modifiedReq);
这对我来说是这样的:
const headersConfig = {
'Accept': 'application/json', //default headers
};
...
if (token) {
headersConfig['Authorization'] = `Bearer ${token}`;
}
...
return next
.handle(request.clone({
setHeaders: headersConfig
}))
我错了。在更新克隆请求时,angular将把新的头放在名为“lazyUpdate”的字段中,而不是直接放在头中。
由于其他原因,请求失败。否,已正确注册。代码确实传递到该拦截器,但未设置标头。@gaetatno如果您使用console.log(令牌),它将打印值,或者它为空或null??它将打印请求。标头似乎未以任何方式设置值。我想问题在于您如何使用if(令牌)因为如果token为null或为空是正确的,您在头中没有值,但是如果token不为null,您不需要modifiedRequest,如果您喜欢我显示的内容
const headersConfig = {
'Accept': 'application/json', //default headers
};
...
if (token) {
headersConfig['Authorization'] = `Bearer ${token}`;
}
...
return next
.handle(request.clone({
setHeaders: headersConfig
}))