将标记设置为有角的标题

时间:2019-02-11 09:27:13

标签: angular interceptor

我在我的angular 6项目中添加了拦截器,但它们无法启动。我在标头中注入了令牌,但返回响应是状态错误

401 (not authenticated)

我在app.module.ts文件的表提供程序中注入了拦截器,但它也无法正常工作。

代码拦截器:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Injectable, Injector } from '@angular/core';
import { Observable } from 'rxjs';
import {Router} from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(public router:Router) {console.log('here'); }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   const authToken = localStorage.getItem('token');
   console.log(authToken);
   const clonedRequest = req.clone({
            headers: req.headers.set('Content-Type', 'application/json')
            .set('Authorization', 'Bearer '+authToken)

        });

    return next.handle(clonedRequest);
  }
}

在其中插入拦截器的代码app.module中

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { PLATFORM_ID, APP_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';
import { AuthInterceptor } from './services/auth.interceptor';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ContactComponent } from './contact/contact.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ng6-toastr-notifications';
import { FileUploadComponent } from './file-upload/file-upload.component';
@NgModule({
    declarations: [
      AppComponent,
      HeaderComponent,
      FooterComponent,
      LoginComponent,
      RegisterComponent,
      HomeComponent,
      ProfileComponent,
      AboutComponent,
      ServicesComponent,
      ContactComponent,
      FileUploadComponent
    ],
    imports: [
      BrowserModule,
      AppRoutingModule,
      HttpModule,
      HttpClientModule,
      FormsModule,
      BrowserAnimationsModule,
      ToastrModule.forRoot(),
    ],
    providers: [
      AuthInterceptor,
      {
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
      }
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
    constructor(
      @Inject(PLATFORM_ID) private platformId: Object,
      @Inject(APP_ID) private appId: string) {
      const platform = isPlatformBrowser(platformId) ?
        'in the browser' : 'on the server';
      console.log(`Running ${platform} with appId=${appId}`);
    }
}

2 个答案:

答案 0 :(得分:0)

像这样解析令牌。

    const authToken = JSON.parse(localStorage.getItem('token'));

    req = req.clone({
      setHeaders: {
        Authorization: `Bearer ${token.token}`, // Or whatever the property you have, if any.
        'Content-Type': 'application/json'
      }
     });

    return next.handle(req);

这意味着请求不会影响拦截程序特权者,请像这样更改您的提供部分。

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],

答案 1 :(得分:0)

@ dev_2019尝试一次。设置标题如下

   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   const authToken = localStorage.getItem('token');
   const clonedRequest = req.clone({
        headers: new HttpHeaders({
          Authorization: authToken,
          "Content-Type": "application/json"
        })
      });
   return next.handle(clonedRequest);

如@Ramesh所说,使用以下方式更新app.module提供程序

providers: [  {provide: HTTP_INTERCEPTORS,useClass: AuthInterceptor ,multi:true }  ]