5

I am trying to pass my api authtoken via the header. I am new to angular js so i am not able to do that. My code:

$scope.init=function(authtoken,cityname){   
        $scope.authtoken=authtoken;                     
        $scope.cityname=cityname;               
        $http({method: 'GET', url: '/api/v1/asas?city='+$scope.cityname+'&auth='+$scope.authtoken}).success(function(data) {                

Right now I am passing the authtoken in the api url. But I want to pass the token via the header.

2 Answers 2

6

usually you pass auth token in headers. Here is how i did it for one of my apps

angular.module('app', []).run(function($http) {
        $http.defaults.headers.common.Authorization = token;
    });

this will add auth token to headers by default so that you wont have to include is every time you make a request. If you want to include it in every call then it will be something like this

$http({
    method: 'GET', 
    url: '/api/v1/asas?city='+$scope.cityname,
    headers:{
        'Authorization': $scope.authtoken
    }
}).success(function(data) {
    //success response.
}).error(function(error){
    //failed response.
});
Sign up to request clarification or add additional context in comments.

2 Comments

in run how i pass my authtoken .Now i get my authtoken in init function.I try to call authtoken in run but it not work like run(function($http,authtoken)
i dont think you can pass authtoken to run function.
4

You can configure on application run

youapp.run(function($http) {
    $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
});

or pass it throw each request

$http({
    url:'url',
    headers:{
        Authorization : 'Basic YmVlcDpib29w'
    }
})

Angular $Http reference

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.