How to pass authtoken through header using angular js

I am trying to pass my authtoken api through the header. I am new to angular js, so I cannot do this. My code is:

$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) { 

Now I pass authtoken in api url. But I want to pass the token through the header.

+5
source share
2 answers

usually you pass the auth token in the headers. Here is how I did it for one of my applications

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

this will add the auth token to the default headers, so you don’t have to include it 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. }); 
+5
source

You can configure when you start the application

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

or pass it to each request

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

Angular $ Http Link

+4
source

Source: https://habr.com/ru/post/1202971/


All Articles