这似乎是一个简单的案例:我正在尝试添加一个请求拦截器,以使用Angular 1.1.5将OAuth承载令牌添加到$ http请求中。这是我的拦截器:
app.factory('bearerTokenInterceptor', function($injector, $q) {
/*
* This interceptor is available for providers that use the header based
* bearer token for authentication
*/
return {
request: function(config) {
/*
* We need to use $injector to get access to the Token provider within
* the body of the ctor - lest we want circular references created
* by providers that need to use the interceptor (and also need the
* Token provider
*/
var Token = $injector.get('Token');
config.headers.get = {'Authorization': 'Bearer ' + Token.get() };
return config || $q.when(config);
}
};
});
然后
app.config(function(TokenProvider, YammerTokenVerifier, $httpProvider) {
TokenProvider.extendConfig({
authorizationEndpoint: 'https://www.yammer.com/dialog/oauth',
verifyFunc: YammerTokenVerifier
});
/*
* Yammer uses a bearer token - in comes the BearerTokenInterceptor!
*/
$httpProvider.interceptors.push('bearerTokenInterceptor');
});
但是当我真正使用$ http
时$http.get('https://www.yammer.com/api/v1/users/current.json')
.success(function(data) {
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
deferred.reject(data);
});
请求拦截器未被调用。我没有看到任何我正在做的事情,这超出了Angular文档的建议。我错过了什么?
答案 0 :(得分:4)
我尝试了你的代码,没关系。你只需要确保你实际上使用角度js。 1.1.5。试试这个:https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js
由于以前的版本,$httpProvider.interceptors
未定义,并且尝试调用$httpProvider.interceptors.push('bearerTokenInterceptor');
会引发异常。
<强>更新强>
如果您在另一个模块中注册工厂,则需要使用以下代码向该模块添加依赖项:
var app = angular.module('yourapp',['factoryModule']);
app.config(function(TokenProvider, YammerTokenVerifier, $httpProvider) {
TokenProvider.extendConfig({
authorizationEndpoint: 'https://www.yammer.com/dialog/oauth',
verifyFunc: YammerTokenVerifier
});
$httpProvider.interceptors.push('bearerTokenInterceptor');
});