6

I am new to angularjs. I am trying to make an API request that requires authorization. I have included it in the header of the request, but it is still not working. I am sure my access token is working. Any advice?

$scope.fetch = function() {
    $scope.code = null;
    $scope.response = null;
    $http({
        method: $scope.method,
        url: $scope.url,
        cache: $templateCache,
        headers: {
            Authorization: "access token"
        }
    }).
    success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
    }).
    error(function(data, status) {
        $scope.data = data || "Request failed";
        $scope.status = status;
    });
};
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Wes
  • 115
  • 1
  • 4
  • 8
  • Add "Basic " before access token. Possible duplicate of this one here http://stackoverflow.com/questions/11876777/angularjs-set-http-header-for-one-request – bp4D Oct 18 '13 at 21:20

2 Answers2

5

You could use following

 $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";

It will add the above header to every POST call you make from your app. For adding a header common to all method, try following.

$http.defaults.headers.common['Authorization'] = "Bearer " + user.oauthInfo.access_token;
vs4vijay
  • 1,175
  • 3
  • 14
  • 28
  • Anywhere...Best way to put this line in Config part of your code OR even you can create a request interceptor to set header – vs4vijay Mar 21 '14 at 07:19
0

Do you see the header in your browser's network request log for the Request?

If so, is it in the expected format? Typically the "Authorization" header will have something before it, like "Basic " (as DevPat mentions in a comment above) or "Bearer ". What belongs here is dependent on the backend system receiving the request.

Examples of expected header:

Authorization: Bearer access_token
Authorization: Basic access_token
Jay Klehr
  • 469
  • 3
  • 7