如何拦截$ httpBackend调用并在Angular JS中添加令牌验证中间件?

时间:2014-10-20 14:02:40

标签: angularjs

我使用angular的$ httpBackend来模拟后端。

有没有办法拦截$ httpBackend的每个请求以验证令牌?

现在,我可以在每个网址调用中执行此操作,如下图 - 但我想模拟中间件,因此我不需要为每个网址请求执行此操作,例如,如果我有10个。 / p>

angular.module('app')。run(['$ httpBackend','MoviesDataModel',function($ httpBackend,MoviesDataModel){

    $httpBackend.whenPOST('/movies').respond(function(method, url, data, headers) {

        // Check the X-AUTH-TOKEN value.
        var authToken = headers['X-AUTH-TOKEN'];

        // If we have a auth token
        if (authToken === 'headervalue') {
            // Check if the token is valid.
            var params = angular.fromJson(data),
                movie = MoviesDataModel.addOne(params),
                movieId = movie.id; // get the id of the new resource to populate the Location field
            return [201, movie, { Location: '/movies/' + movieId }];
        } else {
            // 401 Unauthorize - The user is not logged in.
            return [401, '', {}];
        }
    });

    $httpBackend.whenGET(/\.html$/).passThrough();

}]);

1 个答案:

答案 0 :(得分:0)

您可以使用decorator拦截对$httpBackend的所有来电,并随意执行任何操作。

angular.module('http-app')
 .config(['$provide',
   function($provide) {

     $provide.decorator('$httpBackend', function($delegate) {

       var interceptedCalls = [],

         //Create a new function that will proxy calls to
         // the  $httpBackend service
         newHttpBackend = function(method, url, post, callback, headers, 
                                   timeout, withCredentials, responseType) {

           //Trivial example of tracking each call
           // and a timestamp
           interceptedCalls.push({
             method: method,
             url: url,
             timestamp: new Date()
           });

           //Now call the original with all the arguments
           return $delegate(method, url, post, callback, headers, 
                            timeout, withCredentials, responseType);

         };

       newHttpBackend.interceptedCalls = interceptedCalls;

       //Return the proxy function
       return newHttpBackend;

     });
   }
]);