无法在http拦截器中设置标头

时间:2019-11-11 16:14:54

标签: angular

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

我的拦截器:

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 {
}

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

2 个答案:

答案 0 :(得分:0)

您在哪里

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}`);

答案 1 :(得分:0)

后端出现问题,我允许cors请求,并且一切正常。