Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

javascript - Setting application wide HTTP headers in AngularJS

Is there a way to set the $httpProvider headers outside of angular.module('myApp', []).config()?

I'm getting an Auth-Token from the server after I login the user, and I need to add it as a HTTP Header to all following requests.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use default headers for angular 1.0.x:

$http.defaults.headers.common['Authentication'] = 'authentication';

or request interceptor for angular 1.1.x+:

myapp.factory('httpRequestInterceptor', function () {
  return {
    request: function (config) {

      // use this to destroying other existing headers
      config.headers = {'Authentication':'authentication'}

      // use this to prevent destroying other existing headers
      // config.headers['Authorization'] = 'authentication';

      return config;
    }
  };
});

myapp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');
});

Since factories/services are singletons, this works as long as you do not need to dynamically change your 'authentication' value after the service has been instantiated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...