AngularJS在每个请求上设置标头

时间:2014-07-16 11:50:14

标签: angularjs restangular

我正在尝试设置标头以在每个请求上发送访问令牌。这就是我的尝试:

.factory("TokenRestangular", "StorageService", function (Restangular, StorageService) {
    return Restangular.withConfig(function (RestangularConfigurer) {


        // Set access token in header.
        RestangularConfigurer.setDefaultHeaders({Authorization:'Bearer '+ StorageService.get("access_token")});
        RestangularConfigurer.setBaseUrl('/api');
    });
})

我收到错误:

Error: [ng:areq] http://errors.angularjs.org/1.2.19/ng/areq?p0=fn&p1=not%20aNaNunction%2C%20got%string
    at Error (native)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:6:450
    at Bb (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:19:68)
    at Ua (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:19:155)
    at rc (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:32:423)
    at Object.d [as invoke] (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:34:398)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:36:288
    at c (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:34:305)
    at d (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:35:6)
    at Object.instantiate (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:35:165) 

1 个答案:

答案 0 :(得分:3)

我认为你的工厂函数传递了太多参数,试试这个:

    .factory("TokenRestangular", function (Restangular, StorageService) {
        return Restangular.withConfig(function (RestangularConfigurer) {
        // Set access token in header.
        RestangularConfigurer.setDefaultHeaders({Authorization:'Bearer '+ StorageService.get("access_token")});
        RestangularConfigurer.setBaseUrl('/api');
    });
})

    .factory("TokenRestangular", ["Restangular", "StorageService", function (Restangular, StorageService) {
        return Restangular.withConfig(function (RestangularConfigurer) {
        // Set access token in header.
        RestangularConfigurer.setDefaultHeaders({Authorization:'Bearer '+ StorageService.get("access_token")});
        RestangularConfigurer.setBaseUrl('/api');
    });
}])

如果你想拥有安全的缩小代码。