我正在使用
HttpInterceptor
接口在HTTP请求中添加授权头。@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private localStorage: LocalStorageService,
private sessionStorage: SessionStorageService
) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!request || !request.url || (/^http/.test(request.url) && !(SERVER_API_URL && request.url.startsWith(SERVER_API_URL)))) {
return next.handle(request);
}
const token = this.localStorage.retrieve('authenticationToken') || this.sessionStorage.retrieve('authenticationToken');
if (!!token) {
request = request.clone({
setHeaders: {
Authorization: 'Bearer ' + token
}
});
}
return next.handle(request);
}
}
我的应用程序模块
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
VistaModule,
LayoutModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
在本地运行完美,但生成prod dist
并上传到服务器时失败。
任何请求都会获得头信息:Object,status:401,statusText:“未经授权”
你能帮我吗?
if(token)
而不是if(!token)
... - TheUnreal