NodeJS HTTP拦截器无法处理服务调用

zc0qhyus  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(101)

我创建了一个拦截器来添加header,这样我就不必手动为每个http请求添加header。但是当我在拦截器中添加服务调用时,它不会触发,我不知道为什么。下面是我的代码。

这是我的拦截器文件

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { GoogleAuthService } from './services/auth/auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: GoogleAuthService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Interceptor: Intercepting request...');
    
    return this.authService.requestToken().pipe(
      switchMap(token => {
        console.log('Interceptor: Token obtained -', token);
        const authRequest = this.addAuthenticationToken(request, token);
        return next.handle(authRequest);
      })
    );
  }

  addAuthenticationToken(request: HttpRequest<any>, token: string) {
    return request.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });
  }
}

字符串
它打印了第一个console.log('Interceptor: Intercepting request...');,但从未进入服务调用以打印第二个console.log('Interceptor: Token obtained -', token);

这是我的服务档案

此函数通过传递目标URL向GCP云函数发出请求,该URL返回我希望传递给拦截器的令牌

import { Injectable, SkipSelf } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class GoogleAuthService {
  audience = 'https://cloud.run.app';

  constructor(private http: HttpClient) {}

  requestToken(): Observable<any> {
    const requestUrl = "https://us-central1-gcp.cloudfunctions.net/get-token"
    const tokenUrl = `${requestUrl}?url=${this.audience}`
    return this.http.get(tokenUrl)
  }
}


这工作正常,如果我不进行任何服务调用并硬编码令牌,如下所示,当我进行服务调用以获取令牌时,问题就会出现

import { Injectable, SkipSelf } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpClient } from '@angular/common/http';
import { Observable, from, tap } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { GoogleAuthService } from './services/auth/auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  token: string = "5dadbb1d-03fc-11ed-baea-7640edfdd6b4";
  constructor(private httpClient: HttpClient, private authService: GoogleAuthService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(this.addAuthenticationToken(request));
  }

  addAuthenticationToken(request: HttpRequest<any>) {
    return request.clone({
      setHeaders: {
        Authorization: `Basic ${this.token}`
      }
    })
  }
}

这是我的模块文件

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GoogleAuthService } from './services/auth/auth.service';
import { AuthInterceptor } from './auth.interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true,
      deps: [GoogleAuthService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

浏览器窗口截图


的数据

kdfy810k

kdfy810k1#

当服务本身发出请求时,拦截器应该跳过对服务的调用。

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  token: string = "5dadbb1d-03fc-11ed-baea-7640edfdd6b4";
  constructor(private httpClient: HttpClient, private authService: GoogleAuthService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if(request.url.includes('get-token') {
      return next.handle(request);
    } 

    return next.handle(this.addAuthenticationToken(request));
  }

  addAuthenticationToken(request: HttpRequest<any>) {
    return request.clone({
      setHeaders: {
        Authorization: `Basic ${this.token}`
      }
    })
  }
}

字符串

相关问题