47

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

3 Answers 3

87

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');
});

Sign up to request clarification or add additional context in comments.

5 Comments

May be a silly question to ask, but why the authorization token has prefix "Basic " ?
it's just an example :)
@TheLittleNaruto The Authorization header has a few default options such as Basic base64encodedStringSeperatedWithA: or Bearer tokenString in the form of Authorization: <type> <credentials> which is standard throughout the internet.
@DeanMeehan Thanks. You're not to late to reply, it's just one year anyway.
Stackoverflow will last forever, I just thought I'd leave some information for others searching the same question! :)
23

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 Comments

Problem with this if user logs in after run time he doesn't ave authorization token yet, that's why better use interceptor
Yup, I know that but I answered according to the question as the author wanted to add header in all request:-)
I'm trying this in angular v1.0.6 but the property 'common' does not exist. Any ideas?
0
  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
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.