我有一个正在命中节点API的angular应用程序。我们的后台开发者已经在API上实现了基本身份验证,我需要在我的请求中发送一个auth头部。
我已经追踪到:
$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);我试过了:
.config(['$http', function($http) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);
}])并将其直接附加到请求中:
$http({method: 'GET', url: url, headers: {'Authorization': 'Basic auth'}})})但是什么都不起作用。如何解决这个问题?
发布于 2014-03-20 05:05:36
您混合了这两种用例;实例化服务($http)不能在配置阶段使用,而提供者不能在run块中工作。从module docs
因此,请使用以下两种方法之一:
app.run(['$http', function($http) {
$http.defaults.headers.common['Authorization'] = /* ... */;
}]);app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = /* ... */;
}])发布于 2014-06-10 02:53:54
我有一个服务工厂,它有一个角度请求拦截器,如下所示:
var module = angular.module('MyAuthServices', ['ngResource']);
module
.factory('MyAuth', function () {
return {
accessTokenId: null
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('MyAuthRequestInterceptor');
})
.factory('MyAuthRequestInterceptor', [ '$q', '$location', 'MyAuth',
function ($q, $location, MyAuth) {
return {
'request': function (config) {
if (sessionStorage.getItem('accessToken')) {
console.log("token["+window.localStorage.getItem('accessToken')+"], config.headers: ", config.headers);
config.headers.authorization = sessionStorage.getItem('accessToken');
}
return config || $q.when(config);
}
,
responseError: function(rejection) {
console.log("Found responseError: ", rejection);
if (rejection.status == 401) {
console.log("Access denied (error 401), please login again");
//$location.nextAfterLogin = $location.path();
$location.path('/init/login');
}
return $q.reject(rejection);
}
}
}]);然后,在登录到我的登录控制器时,我使用下面这行代码存储accesstoken:
sessionStorage.setItem('currentUserId', $scope.loginResult.user.id);
sessionStorage.setItem('accessToken', $scope.loginResult.id);
sessionStorage.setItem('user', JSON.stringify($scope.loginResult.user));
sessionStorage.setItem('userRoles', JSON.stringify($scope.loginResult.roles));这样,我就可以在登录后为每个请求分配标头。这就是我的做法,完全值得批评,但它似乎工作得很好。
发布于 2013-09-19 02:43:22
您可以在控制器中使用它:
.controller('Controller Name', ['$http', function($http) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password;
}]);https://stackoverflow.com/questions/18877715
复制相似问题