AngularJS $http custom header for all requests

2019-01-13 09:55发布

问题:

I was wondering if there is any way to configure all $http requests header with adding custom info. Something like config :

 var config = {headers: {
            'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
            'Accept': 'application/json;odata=verbose'
        }
    };

But for all $http calls I will make in different services. I'm sure there is a solution :D.Thanks

回答1:

You can create a $http interceptor to extend your header:

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

      config.headers['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';
      config.headers['Accept'] = 'application/json;odata=verbose';

      return config;
    }
  };
});

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



回答2:

A simpler solution could be to use Angular's run block:

app.run(['$http', function ($http) {
    $http.defaults.headers.common['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';
    $http.defaults.headers.common['Accept'] = 'application/json;odata=verbose';
}]);

Note: This solution allows you to pass the static value only one time since the run block executes only once.



回答3:

  use the folllowing code and  you can also control  $http timeout from 
 config setting.    
 'use strict';
   var app = angular.module('b2capp', []);
   var apiRequestCount = 0;      
   app.config(function ($httpProvider) {
      $httpProvider.interceptors.push(function ($rootScope, $q) {
       return {
           request: function (config) {
               apiRequestCount++;
                //   config.timeout =300000;
              return config;
          },
          response: function (response) {
               return response;
          },
           responseError: function (rejection) {
             switch (rejection.status) {
                   case 408:
                        console.log('connection timed out');
                        break;
              }
               // return $q.reject(rejection);
               return rejection;
            }
          }
       })
    });
 }]);
   app.controller('myCtrl', function ($scope, $http, $timeout) {
    var headers = {
            //'Authorization': 'Basic ' + btoa(username + ":" + password),
               'Access-Control-Allow-Origin': true,
               'Content-Type': 'application/json; charset=utf-8',
               "X-Requested-With": "XMLHttpRequest"
                 }
    $http.post(url + 'Search_6e', reqCookie, {
                   headers
            })
            .then(function Success(response) {               
                 $scope.myData = resultData;
                 console.log($scope.myData);
           }, function myError(response) {
              //error code
    });