【问题标题】:Cant set header in http interceptor无法在 http 拦截器中设置标头
【发布时间】:2019-11-12 17:10:35
【问题描述】:

我使用 HttpInterceptor 在标头中设置 jwt 令牌,但 request.clone 方法无法正常工作。出于某种原因,它在 headers.lazyUpdate 数组中添加了标头。

我的拦截器:

import { Injectable } from '@angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders} from '@angular/common/http';
import { Observable } from 'rxjs';
import {AuthenticationService} from '../services/authentication.service';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(private authenticationService: AuthenticationService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add authorization header with jwt token if available
    const currentUser = this.authenticationService.currentUserValue;
    if (currentUser && currentUser.token) {
      request = request.clone({
        setHeaders: {
          Authorization: `${currentUser.token}`
        }
      });
      return next.handle(request);
    } else {
      return next.handle(request);
    }
  }
}

并将其添加到module.ts中

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {AuctionCarouselComponent} from './shared/components/auction-carousel/auction-carousel.component';
import {AuctionFooterComponent} from './shared/components/auction-footer/auction-footer.component';
import {AuctionNavbarComponent} from './shared/components/auction-navbar/auction-navbar.component';
import {AuctionSearchComponent} from './shared/components/auction-search/auction-search.component';
import {AuctionStarsComponent} from './shared/components/auction-stars/auction-stars.component';
import {AuctionProductItemComponent} from './shared/components/auction-product-item/auction-product-item.component';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {AuctionProductDetailComponent} from './shared/components/auction-product-detail/auction-product-detail.component';
import {AuctionHomeComponent} from './shared/components/auction-home/auction-home.component';
import {RouterModule, Routes} from '@angular/router';
import {PageNotFoundComponent} from './shared/components/page-not-found/page-not-found.component';
import {UnsavedChangesGuard} from './routs-activators/usaved-changes-guard';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {LoginComponent} from './shared/components/login/login.component';
import {FilterPipe} from './pipes/filter-pipe';
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import {ProductService} from './services/product-service';
import {AuthenticationService} from './services/authentication.service';
import {AuctionAboutComponent} from './shared/components/auction-about/auction-about.component';
import {AuthGuard} from './routs-activators/auth-guard';
import {JwtInterceptor} from './routs-activators/jwt-interceptor';
import {ErrorInterceptor} from './routs-activators/error-interceptor';
import { AuctionRegistrationComponent } from './shared/components/auction-registration/auction-registration.component';
import {AlertService} from './services/alert-service';
import { AuctionAlterComponentComponent } from './shared/components/auction-alter-component/auction-alter-component.component';


const appRoutes: Routes = [
  {path: '', component: AuctionHomeComponent, canDeactivate: [UnsavedChangesGuard]},
  {path: 'login', component: LoginComponent},
  {path: 'register', component: AuctionRegistrationComponent},
  {path: 'products', component: AuctionHomeComponent, canActivate: [AuthGuard]},
  {path: 'products/:productId', component: AuctionProductDetailComponent, canActivate: [AuthGuard]},
  {path: 'about', component: AuctionAboutComponent, canActivate: [AuthGuard]},
  {path: '**', component: PageNotFoundComponent}
];


@NgModule({
  declarations: [
    AppComponent,
    AuctionCarouselComponent,
    AuctionFooterComponent,
    AuctionNavbarComponent,
    AuctionSearchComponent,
    AuctionStarsComponent,
    AuctionStarsComponent,
    AuctionProductItemComponent,
    AuctionProductDetailComponent,
    AuctionHomeComponent,
    PageNotFoundComponent,
    LoginComponent,
    FilterPipe,
    AuctionAboutComponent,
    AuctionRegistrationComponent,
    AuctionAlterComponentComponent
  ],
  imports: [
    BrowserModule,
    NgbModule,
    RouterModule.forRoot(appRoutes), // for routing
    FormsModule, // if you want to use [(ngModel)] then you have to import FormsModule in app.module.ts
    ReactiveFormsModule, // to use reactive forms
    HttpClientModule // for http requests
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
    ProductService, UnsavedChangesGuard, AuthenticationService, AuthGuard, AlertService ],
  bootstrap: [AppComponent],
  exports: []
})
export class AppModule {
}

在网络中,我在请求中找不到标头。

【问题讨论】:

  • 你在延迟加载模块中使用这个吗?
  • @robert,我只使用一个模块:app.module.ts
  • 你也可以分享那个代码吗?
  • 罗伯特,我更新了帖子
  • 谢谢,什么版本的 Angular?

标签: angular


【解决方案1】:

你在哪里

request = request.clone({
    setHeaders: {
      Authorization: `${currentUser.token}`
    }
  });
  return next.handle(request);    

改为这样做

const headers = request.headers.set('Authorization', currentUser.token);
return next.handle(request.clone({ headers });

如果这是一个不记名令牌,你可能想做Bearer ${currentUser.token}

const headers = request.headers.set('Authorization', `Bearer ${currentUser.token}`);

【讨论】:

    【解决方案2】:

    后端有问题,我允许 cors 请求,一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2018-01-31
      • 2019-12-03
      • 2018-06-21
      相关资源
      最近更新 更多