2

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

});
isuruAb
  • 2,202
  • 5
  • 26
  • 39
user1673498
  • 431
  • 1
  • 8
  • 26

2 Answers2

1

Citing this topic:

How to use Basic Auth with jQuery and AJAX?

So, in Angular, it would be:

$http({
      method: "GET",
      url: "https://APIURlGoesHere" + $scope.search,
     headers: { 'Authorization' : 'Basic '+btoa(username + ":" + password) 
     })
.then(function(response) {
  $scope.details = response.data;
});
Community
  • 1
  • 1
dev8080
  • 3,950
  • 1
  • 12
  • 18
  • This approach has an inconvenient: the header needs to be set this way on every service call that is implemented. For instance: If the way the header is received, is changed by your api provider (no very common, but it can happen), you have to change this implementation on every file of your project the header was set this way (it can be thousands). Not very nice. – lealceldeiro Feb 06 '17 at 19:09
1

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.

Community
  • 1
  • 1
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80