简体   繁体   English

angular4拦截器导致重复的http请求

[英]angular4 interceptor causes duplicated http requests

Here is my interceptor 这是我的拦截器

// src/app/auth/token.interceptor.ts
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpErrorResponse,
  HttpInterceptor
} from '@angular/common/http';
import { JwtService } from '@app/services/jwt.service';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor(public jwtService: JwtService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const headersConfig = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };

    if (this.jwtService.getToken()) {
      headersConfig['Authorization'] = `Bearer ${this.jwtService.getToken()}`;
    }

    request = request.clone({
      setHeaders: headersConfig
    });
    return next.handle(request).do((event: HttpEvent<any>) => {

    }, (err: any) => {

    });
  }
}

and my app.module, everything like in documentation 和我的app.module,一切都像在文档中

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    SidebarComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes
      , { preloadingStrategy: PreloadAllModules }
    ),
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MyInterceptor,
      multi: true
    },
    JwtService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

This causes duplicated http requests 这会导致重复的http请求 在此输入图像描述

I found that when I remove setHeaders option, the problem is fixed, but I created intercepter to add authorization header in the first place. 我发现当我删除setHeaders选项时,问题已解决,但我创建了截取器以首先添加授权标头。 Please help me to understand what's wrong 请帮我理解什么是错的

When you have an authenticated request initially there is one request of the type OPTIONS that is done during the called preflight. 当您最初有一个经过身份验证的请求时,在调用的预检期间会有一个OPTIONS类型的请求。 It's a kind of handshake with the server figuring out if it accepts requests of that type. 这是与服务器的一种握手,确定它是否接受该类型的请求。 If all goes OK it will then do the actual GET, POST, etc. request you initially did. 如果一切顺利,它将执行您最初做的实际GET,POST等请求。 I believe that's what you're experiencing. 我相信这就是你所经历的。

Edit 编辑

Your problem might reside in the way you are setting the headers. 您的问题可能在于设置标头的方式。

Try the following 请尝试以下方法

request = request.clone({
      headers: headersConfig
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM