$http Auth Headers in AngularJS

前端 未结 8 750
闹比i
闹比i 2020-11-30 21:52

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.

8条回答
  •  醉话见心
    2020-11-30 22:24

    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'] = /* ... */;
    }])
    

提交回复
热议问题