this should be quite easy, but in the end is not working :(. We use Angular 1.4.3 , and we try to add an Authorization header value before some API calls.
Long story short, there is a factory:
angular.module('xxx').factory('factory', function ($resource, addBasicAuth) {
return $resource(baseUrl, {}, {
query: {method: 'GET', isArray: true, transformRequest: addBasicAuth},
...
});
});
And the addBasicAuth
goes as follows:
angular.module('xxx').factory('addBasicAuth', function ($rootScope) {
return function (data, headersGetter) {
var user = ($rootScope.user);
headersGetter().Authorization = 'Basic ' + Base64.encode(user.username + ':' + user.password);
return angular.toJson(data);
};
});
And in theory all should work fine, but for the reason I do not understand, the requestHeader is untouched (checked in Developers Tools/Network - Chrome).
What am I doing wrong? Thanks!
my colleague helped me out with a following solution;
instead of transformRequest
we use headers
and it goes like this:
angular.module('xxx').factory('factory', function ($resource, addBasicAuth) {
return $resource(baseUrl, {}, {
query: {
method: 'GET',
isArray: true,
headers: addBasicAuth()
},
...
});
});
and the addBasicAuth
is now a factory function:
angular.module('xxx').factory('addBasicAuth', function ($rootScope) {
return function () {
var user = ($rootScope.user);
return {'Authorization': 'Basic ' + Base64.encode(user.username + ':' + user.password)};
};
});
Works like a charm.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.