How to add multiple headers in Angular 5 HttpInterceptor

后端 未结 6 683
情话喂你
情话喂你 2020-12-09 15:16

I\'m trying to learn how to use HttpInterceptor to add a couple of headers to each HTTP request the app do to the API. I\'ve got this interceptor:



        
相关标签:
6条回答
  • 2020-12-09 15:36

    I have tried following ways to send custom headers using interceptors. please check the link stackBlitz

    Please refer the console screenshot for your reference browser console-request header

    And the custom headers are added in

    access-control-request-headers:authkey,content-type,deviceid

    I want the headers to be added as part of header, not inside access-control-request-headers. Please suggest me on this

    0 讨论(0)
  • 2020-12-09 15:37
      const modifiedReq = req.clone({
          url: this.setUrl(req.url),
          headers: this.addExtraHeaders(req.headers)
        });
    

    And the method:

    private addExtraHeaders(headers: HttpHeaders): HttpHeaders {
      headers = headers.append('myHeader', 'abcd');
      return headers;
    } 
    

    The method .append creates a new HttpHeaders object adds myHeader and returns the new object.

    Using this solution means that you can also use multiple interceptors because you will not overwrite your headers.

    0 讨论(0)
  • 2020-12-09 15:38

    in your interceptor file

    import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
    import {Injectable} from '@angular/core';
    import {Observable} from 'rxjs';
    @Injectable()
    export class fwcAPIInterceptor implements HttpInterceptor {
      intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
      const auth = req.clone({
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'Auth-Token': 'jwtToken'
        })
      });
    
    
    
      return next.handle(auth);
    }
    
    
    
     **in app module**
    
    import {HTTP_INTERCEPTORS} from '@angular/common/http';
    
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule
      ],
      providers: [
        {provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptorService, multi: true},
      ],
      bootstrap: [AppComponent]
    })
    
    0 讨论(0)
  • 2020-12-09 15:45

    Since the set method returns headers object every time, you can do this. This way, original headers from the intercepted request will also be retained.

    const authReq = req.clone({
        headers: req.headers.set('Content-Type', 'application/json')
        .set('header2', 'header 2 value')
        .set('header3', 'header 3 value')
    });
    
    0 讨论(0)
  • 2020-12-09 15:46

    Edit: Following suggestions in comments I have unified both answers

    Overwriting all headers

    @Injectable()
    export class fwcAPIInterceptor implements HttpInterceptor {
      intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
      const authReq = req.clone({
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'Authorization': 'my-auth-token'
        })
      });
    
      console.log('Intercepted HTTP call', authReq);
    
      return next.handle(authReq);
    }
    

    Adding more headers without overwriting (credits to Ketan Patil - see answer in this post)

    const authReq = req.clone({
        headers: req.headers.set('Content-Type', 'application/json')
            .set('header2', 'header 2 value')
            .set('header3', 'header 3 value')
    });
    
    0 讨论(0)
  • 2020-12-09 15:59

    As mentioned before - accepted method overrides headers, for adding them I like approach from API documentation:

    const authReq = req.clone({ setHeaders: { Authorization: authToken } });
    
    0 讨论(0)
提交回复
热议问题