Wes
Wes

Reputation: 115

AngularJS How to include header in Http request

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

Upvotes: 6

Views: 9427

Answers (2)

vs4vijay
vs4vijay

Reputation: 1205

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;

Upvotes: 5

Jay Klehr
Jay Klehr

Reputation: 469

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

Upvotes: 0

Related Questions