angularjs - Why won't $http set a default header? -


$http.post('http://localhost:7001/v1/sessions', {   data: {     username: $scope.user.username,     password: $scope.user.password,     type: 'sessions'   } }) .then(function(response) {   if(response.data.data.token) {     $http.defaults.headers.common.authorization = response.data.data.token;     $state.go('app.dashboard');   } else {     $scope.autherror = response;   } }, function(x) {   $scope.autherror = 'server error'; }); 

i can confirm if condition gets called , response.data.data.token present.

it goes app.dashboard state intercepted ui-router:

$stateprovider.state('app', {   abstract: true,   url: '/app',   templateurl: 'tpl/app.html',   resolve: {     current_user: ['$http', function($http) {       return $http.get('http://localhost:7001/v1/users/4/entities');     }]   } }) 

that call, however, not have set in header. thought $http.defaults set default value in header. doing incorrectly?

you must set default headers in config method , not in service.

example:

myapp.config(['$httpprovider', function ($httpprovider) {     $httpprovider.defaults.headers.common['content-type'] = 'application/json; charset=utf-8'; }]); 

only in config can configure httpprovider. if try inside service, won't affect $httpprovider service @ all.

edit:

you must make use interceptors in scenario.

for purposes of global error handling, authentication, or kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, desirable able intercept requests before handed server , responses before handed on application code initiated these requests.

refer angular docs interceptor section

just sample code:

app.service('apiinterceptor', function($rootscope, userservice) {     var service = this;      service.request = function(config) {         // check if token available. once token available here userservice.         var access_token = userservice.gettoken() || "unauthorized";         if (access_token) {             config.headers.authorization = access_token;         }         return config;     };      service.responseerror = function(response) {         return response;     }; }) 

in config

$httpprovider.interceptors.push('apiinterceptor'); 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -