AngularJS 中的 $http Auth 标头 [英] $http Auth Headers in AngularJS
本文介绍了AngularJS 中的 $http Auth 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个正在访问节点 API 的 Angular 应用程序.我们的后端开发人员已经在 API 上实现了基本的身份验证,我需要在我的请求中发送一个身份验证头.
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.
我已经找到了:
$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);
我试过了:
.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?
推荐答案
你正在混合用例;实例化服务 ($http
) 不能在配置阶段使用,而提供程序在运行块中不能工作.来自模块文档:
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'] = /* ... */;
}])
这篇关于AngularJS 中的 $http Auth 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文