簡體   English   中英

Angular HTTP 攔截器未修改 HTTP 請求標頭

[英]Angular HTTP interceptor not modifying HTTP request headers

我正在使用 Angular 13,嘗試將 JWT 添加到標頭以訪問后端的受限路由。 經過后端檢查,JwtInterceptor 似乎沒有修改 HTTP 請求標頭。 在我的項目中,我只在根 AppModule 中包含了一次 HttpClientModule。 I've appended a pipe function with error catching to my next object (inside of interceptor) in an effort to debug as suggested by someone with a similar issue on SO to no avail, removed pipe funct for brevity.

我已經像文件中的 console.log'ing 一樣基本,但沒有 output 來解釋它,所以我懷疑攔截器根本沒有觸發。

我以前和攔截器合作過,沒有遇到過這個問題,所以我很難過。 這里唯一的區別是我正在使用 Angular PWA,如果我理解正確,服務工作者不應該阻礙攔截器的行為嗎? 我知道 POST 請求將屬於“緩存破壞”事件?

也許錯誤在於 PWA 的實施? 在這種情況下,我確實遵循了文檔。

附件是 HttpInterceptors 的 App Module、Jwtinterceptor 和“Barrel”,我計划在項目中添加更多的攔截器,所以我按照文檔的建議創建了 Barrel。

TL;博士
我的 HttpInterceptor (JwtInterceptor) 似乎根本沒有觸發。 這個實現在過去的項目中對我有用,唯一的區別是這個項目是一個 PWA。 不確定這是否與 PWA 實施存在沖突或怪癖。 HttpClientModule 在項目中只包含一次。

app.module.ts

//Angular level imports
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

//App level components
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './header/header.component';
import { AngularMaterialModule } from './_material/material.module';
import { UploadDirective } from './directives/upload.directive';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { ThanksComponent } from './thanks/thanks.component';
import { PhotoAlbumsComponent } from './photo-albums/photo-albums.component';
import { DialogComponent } from './dialog/dialog.component';
import { AlbumComponent } from './album/album.component';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';
import { ForgotPasswordComponent } from './forgot-password/forgot-password.component';
import { ResetPasswordComponent } from './reset-password/reset-password.component';
import { ThanksBotDownloadComponent } from './thanks-bot-download/thanks-bot-download.component';
import { ErrorBotDownloadComponent } from './error-bot-download/error-bot-download.component';
import { RouterModule } from '@angular/router';
import { httpInterceptorProviders } from './_interceptors/index';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    HeaderComponent,
    UploadDirective,
    LoginComponent,
    RegisterComponent,
    ThanksComponent,
    PhotoAlbumsComponent,
    AlbumComponent,
    DialogComponent,
    ForgotPasswordComponent,
    ResetPasswordComponent,
    ThanksBotDownloadComponent,
    ErrorBotDownloadComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    AngularMaterialModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: environment.production,
      // Register the ServiceWorker as soon as the app is stable
      // or after 30 seconds (whichever comes first).
      registrationStrategy: 'registerWhenStable:30000',
    }),
    HttpClientModule,
    RouterModule,
  ],
  providers: [httpInterceptorProviders],
  bootstrap: [AppComponent],
})
export class AppModule {}

jwt.interceptor.ts

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { environment } from '@environments/environment';
import { AccountService } from '@app/_services/account.service';


@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(private accountService: AccountService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // add auth header with jwt if user is logged in and request is to the api url
    //console.log("JWT Interceptor");
    const user = this.accountService.currentUserValue;
    const isLoggedIn = user && user.jwt;
    const isApiUrl = request.url.startsWith(environment.apiUrl);
    if (isLoggedIn && isApiUrl) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${user.jwt}`,
        },
      });
    }

    return next.handle(request);
  }
}

index.ts “桶”文件

/* "Barrel" of Http interceptors */
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './jwt.interceptor';

/* Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
];

發布請求標頭后端請求標頭

而不是setHeaders嘗試headers

request = req.clone({
    headers: req.headers.append('Authorization', `Bearer ${user.jwt}`)
});

感謝幫助過的人。

這個問題與將我的應用程序變成 PWA 有關。 服務人員正在影響我的令牌攔截器。 我在沒有 PWA 的情況下重新制作了我的應用程序,並且按預期工作。 因此,如果您的攔截器停止工作后服務工作者實現,請務必小心,它實際上可能不是您的攔截器。

我建議任何有興趣將其轉換為 PWA 的工作應用程序來閱讀文檔但遵循更全面的教程的人,因為我確實覺得更高級主題的 Angular 文檔是在真空中編寫的並且缺乏上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM