繁体   English   中英

如何为不同的请求(URL)拆分拦截器?

[英]How to split interceptor for different requests (URLs)?

首先,我有带有头的configAuth ,包括每个Controller的JWT令牌。

var configAuth = {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token')
    }
};

但是现在,当我拥有大量控制器时,我意识到我需要为此做些事情。 我听说过interceptors并试图得到它们。

我知道我不能只对每个请求添加令牌,因为有些页面和请求(例如/login根本不应该具有Authorization令牌。 而获得带有Authorization header html文件在某种程度上给了我一个例外。 所以我试图像这样拆分请求:

angular.module('App')

.factory('sessionInjector',['$injector', function ($injector) {
    var sessionInjector = {
        request: function (config) {
            if (config.url == "/one" || config.url == "/two"){
                config.headers['Content-Type'] = 'application/json;charset=utf-8;';
                config.headers['Authorization'] = localStorage.getItem('token');
            } else {
                config.headers['Content-Type'] = 'application/json;charset=utf-8;';
            }
            return config;
        },
        response: function(response) {
            if (response.status === 401) {
                var stateService = $injector.get('$state');
                stateService.go('login');
            }
            return response || $q.when(response);
        }
    };
    return sessionInjector;
}]);

但这不适用于/one/{one_id}类的请求,因此我无法对所有可能性进行硬编码。 那么,最佳实践是什么?

有一种更好的方法。 登录后,将身份验证令牌设置到$ http服务的标头中。 这样就无需在每个调用中传递config对象。

登录 :

function Login(credentials){
    $http.post(apiPath, credentials).then(function (data) {
         $http.defaults.headers.common['Authorization'] = data['token'];
    });
}

此后的所有HTTP调用都将设置Authorization标头。

但是有些调用不需要授权,在这种情况下,您可以编写一个函数,该函数具有自己的配置对象,而标头中没有授权。

未经授权的功能:

function Without_Auth(url, data) {
    var deferred = $q.defer();
    var responsePromise = $http({
        method: 'post',
        url: url,
        data: data,
        headers: {
            'Content-Type': 'application/json;charset=utf-8;'
        }
    })
    responsePromise.success(function (data) {
        deferred.resolve(data);
    });
    responsePromise.error(function (err) {
        deferred.reject();
    });
    return deferred.promise;
}

希望这能解决您的问题!

您现在拥有的是一个很好的起点。 我假设您的大多数API都需要auth令牌,因此设置哪些端点不需要auth可能是更快的方法。 我尚未对此进行测试,但它可能会让您步入正轨。 我将注射器设置为提供程序,以便您可以在配置中配置匿名路由规则。

angular.module('App')
    .provider('sessionInjector',[function () {
        var _anonymousRouteRules;

        this.$get = ['$injector', getSessionInjector];
        this.setupAnonymousRouteRules = setupAnonymousRouteRules;

        function getSessionInjector($injector) {
            var service = {
                request: requestTransform,
                response: responseTransform
            };

            function requestTransform(config) {         
                if (!isAnonymousRoute(config.url)){
                    config.headers['Authorization'] = localStorage.getItem('token');
                }

                config.headers['Content-Type'] = 'application/json;charset=utf-8;';

                return config;
            }

            function responseTransform(response) {
                if (response.status === 401) {
                    var stateService = $injector.get('$state');
                    stateService.go('login');
                }
                return response || $q.when(response);
            }

            return service;
        }

        function isAnonymousRoute(url) {
            var isAnonymous = false;
            angular.forEach(_anonymousRouteRules, function(rule) {
                if(rule.test(url)) {
                    isAnonymous = true;
                }
            });
            return isAnonymous;
        }

        function setupAnonymousRouteRules(anonymousRouteRules) {
            _anonymousRouteRules = anonymousRouteRules;
        }
    }]);

这样,您可以通过为URL传入一组正则表达式来配​​置规则:

angular.module('App').config(['sessionInjectorProvider', config]);

function config(sessionInjectorProvider) {
    sessionInjectorProvider.setupAnonymousRouteRules([
        /.*\.html$/,
        /^\/login$/
    ]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM