Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

$http Auth Headers in AngularJS

I have an angular application that is hitting a node API. Our backend developer has implemented basic auth on the API, and I need to send an auth header in my request.

I've tracked down:

$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);

I've tried:

.config(['$http', function($http) {
       $http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' +    password);
}])

As well as appending it directly to the request:

$http({method: 'GET', url: url, headers: {'Authorization': 'Basic auth'}})})

But nothing works. How to solve this?

question from:https://stackoverflow.com/questions/18877715/http-auth-headers-in-angularjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're mixing the use cases; instantiated services ($http) cannot be used in the config phase, while providers won't work in run blocks. From the module docs:

  • Configuration blocks - […] Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
  • Run blocks - […] Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

So use either of the following:

app.run(['$http', function($http) {
    $http.defaults.headers.common['Authorization'] = /* ... */;
}]);
app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common['Authorization'] = /* ... */;
}])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...