Search code examples
javascriptjqueryangularjsangularjs-scope

Angular JS passes App ID and Key with every request


I have a basic angular APP that makes a GET request call to a API URL. The data returned is in JSON format. The API documentation states the following:

You must provide your App ID and key with every request that you make to the API. To do this, set an HTTP Authorization header on your requests that consists of your ID, followed by a colon, followed by your key, eg abc123:xyz789.

How do I incorporate this to my basic HTTP request.my code is below.

angular.module('myApp', [])
.controller('MyControler', function($scope, $http) {
  $scope.$watch('search', function() {
    fetch();
  });

   $scope.search = "My Search Query";

   function fetch() {
   $http.get("https://APIURlGoesHere" + $scope.search )
    .then(function(response) {
      $scope.details = response.data;
    });

  $http.get("ttps://APIURlGoesHere" + $scope.search)
    .then(function(response) {
      $scope.related = response.data;
    });
  }

});

Solution

  • Best way I know so far to implement this is: Interceptors

    You can find some useful info about it here and here

    And on SO, here: AngularJS $http interceptors

    In your case, basically, you need to create a file with the following implementation (or equivalent) and include it into your project:

    function myInterceptor() {
    
        function request(req) {
    
            var token = "mytoken" ;  //<<--here you need to set the custom header's info (eg: abc123:xyz789)
            var myHeader = "myHeader";  //<<--here you need to set the custom header's name (eg: Authorization)
    
            if (token) {
                //put custom header for sending the token along with every request
                req.headers[myHeader] = token;
            }
    
            return req;
        }
    
        return {
            request: request
        };
    
    };
    
    function conf($httpProvider) {
        $httpProvider['interceptors'].push('myInterceptor');
    };
    
    angular
        .module('your_module_name')
        .factory('myInterceptor', myInterceptor)
        .config(['$httpProvider', conf]);
    

    This will intercept every request made from your frontend app and will include that header on it.