Angular - Set headers for every request

前端 未结 19 1603
[愿得一人]
[愿得一人] 2020-11-22 07:43

I need to set some Authorization headers after the user has logged in, for every subsequent request.


To set headers for a particular request,



        
相关标签:
19条回答
  • 2020-11-22 08:40

    Although I'm answering this very late but if anyone is seeking an easier solution.

    We can use angular2-jwt. angular2-jwt is useful automatically attaching a JSON Web Token (JWT) as an Authorization header when making HTTP requests from an Angular 2 app.

    We can set global headers with advanced configuration option

    export function authHttpServiceFactory(http: Http, options: RequestOptions) {
      return new AuthHttp(new AuthConfig({
        tokenName: 'token',
            tokenGetter: (() => sessionStorage.getItem('token')),
            globalHeaders: [{'Content-Type':'application/json'}],
        }), http, options);
    }
    

    And sending per request token like

        getThing() {
      let myHeader = new Headers();
      myHeader.append('Content-Type', 'application/json');
    
      this.authHttp.get('http://example.com/api/thing', { headers: myHeader })
        .subscribe(
          data => this.thing = data,
          err => console.log(error),
          () => console.log('Request Complete')
        );
    
      // Pass it after the body in a POST request
      this.authHttp.post('http://example.com/api/thing', 'post body', { headers: myHeader })
        .subscribe(
          data => this.thing = data,
          err => console.log(error),
          () => console.log('Request Complete')
        );
    }
    
    0 讨论(0)
提交回复
热议问题