Himanshu Bhuyan Himanshu Bhuyan - 3 months ago 30
AngularJS Question

how to pass authtoken via header using angular js

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.

Answer

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',
    header:{
        'Authorization': $scope.authtoken
    }
}).success(function(data) {
    //success.
}).error(function(error){
    //failed.
});
Comments