javascript - HttpInterceptor 不适用于所有请求
问题描述
我正在使用新版本的 Angular,我面临着在所有请求的请求标头中未发送授权令牌的问题。自从我升级到新版本 8 后,我检查了所有内容,但问题仍然存在。当我发送一些请求时,即使我在控制台中打印它以检查它的存在,我也找不到授权标头。
这是 Angular 8 的新版本。
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpEvent,
HttpHandler,
HttpRequest
} from '@angular/common/http';
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
req: HttpRequest,
next: HttpHandler
): Observable> {
// Retrieve logged in user if connected
const userToken = this.authService.getAuthenticatedUser();
// Verify existing of the user
if (userToken != null && userToken.bearerToken != null) {
req = req.clone({
setHeaders: {
Authorization: userToken.bearerToken
}
});
}
return next.handle(req);
}
}
app.module.ts
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
FooterComponent,
HomeComponent,
ContactUsComponent,
NotFoundComponent,
CartComponent,
LoginComponent
],
imports: [BrowserModule, AppRoutingModule, CustomModule, LayoutModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
我期待有授权标头。
解决方案
导入HTTP_INTERCEPTORS
和您的服务并在提供程序中提供它们
<! app.module.ts -->
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { RequestInterceptor } from './your-interceptor-path'
@NgModule({
declarations: [...],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor,
multi: true
}
]
您仅将
Authorization
标头克隆到HttpRequest
将以下行添加到标题克隆RequestInterceptor
旁边的服务中Authorization
if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
推荐阅读
- python-3.x - CNN - 如何使用 keras 正确获取 val_loss 和 val_acc?
- mvvm - 如何使用 MVVM 为社区工具包 RadialGauge 制作动画?
- google-apps-script - 从 Google 表格发送提醒电子邮件和日历
- amazon-web-services - 更新 AWS Glue 表中的行/列
- bash - 如何使用 sed 或 grep 和正则表达式 json 提取文本
- javascript - Vue-ChartJS 数据集推送不更新图表
- java - MongoDB & Java:检索按索引排序的记录
- c++17 - 我需要一些帮助才能在 C++17 中获得正确的十进制输出流格式
- javascript - 在新窗口中打开组件,无需引导
- javascript - 尝试将 selenium 用于动态类自动化