Angular - Set headers for every request

前端 未结 19 1972
[愿得一人]
[愿得一人] 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:23

    Extending BaseRequestOptions might be of great help in this scenario. Check out the following code:

    import {provide} from 'angular2/core';
    import {bootstrap} from 'angular2/platform/browser';
    import {HTTP_PROVIDERS, Headers, Http, BaseRequestOptions} from 'angular2/http';
    
    import {AppCmp} from './components/app/app';
    
    
    class MyRequestOptions extends BaseRequestOptions {
      constructor () {
        super();
        this.headers.append('My-Custom-Header','MyCustomHeaderValue');
      }
    } 
    
    bootstrap(AppCmp, [
      ROUTER_PROVIDERS,
      HTTP_PROVIDERS,
      provide(RequestOptions, { useClass: MyRequestOptions })
    ]);
    

    This should include 'My-Custom-Header' in every call.

    Update:

    To be able to change the header anytime you want instead of above code you can also use following code to add a new header:

    this.http._defaultOptions.headers.append('Authorization', 'token');
    

    to delete you can do

    this.http._defaultOptions.headers.delete('Authorization');
    

    Also there is another function that you can use to set the value:

    this.http._defaultOptions.headers.set('Authorization', 'token');
    

    Above solution still is not completely valid in typescript context. _defaultHeaders is protected and not supposed to be used like this. I would recommend the above solution for a quick fix but for long run its better to write your own wrapper around http calls which also handles auth. Take following example from auth0 which is better and clean.

    https://github.com/auth0/angular2-jwt/blob/master/angular2-jwt.ts

    Update - June 2018 I see a lot of people going for this solution but I would advise otherwise. Appending header globally will send auth token to every api call going out from your app. So the api calls going to third party plugins like intercom or zendesk or any other api will also carry your authorization header. This might result into a big security flaw. So instead, use interceptor globally but check manually if the outgoing call is towards your server's api endpoint or not and then attach auth header.

提交回复
热议问题