【问题标题】:angular auth interceptor on selected request所选请求的角度身份验证拦截器
【发布时间】:2017-04-12 02:53:15
【问题描述】:

我已经编写了一个身份验证拦截器,它将身份验证令牌添加到请求中,并在用户未登录时处理身份验证错误。

var storeApp = angular.module('storeApp');

storeApp.factory('authInterceptor', function ($q, $window) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.token) {
                config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
            return config;
        },
        response: function (response) {
            return response || $q.when(response);
        },
        responseError: function (response) {
            if (response.status === 401 || response.data.error === 'token_not_provided') {
                console.log('auth error');
            }
            return $q.reject(response);
        }
    };
});

storeApp.config(function ($httpProvider) {
    $httpProvider.defaults.withCredentials = true;
    $httpProvider.interceptors.push('authInterceptor');
});

问题是身份验证拦截器被添加到每个请求中,无论请求是否需要身份验证。创建仅在路由需要身份验证时拦截的身份验证拦截器的最佳方法是什么?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    你需要在 authInterceptor 工厂方法中过滤掉你想要的请求

    ['/whatever/1', '/whatever/2', '/whatever/3'].forEach(function(value){
     if (response.config.url.startsWith(value)) {
       // do something
     }
    })
    
    
    return response;
    

    【讨论】:

      猜你喜欢
      • 2016-08-07
      • 2021-07-05
      • 1970-01-01
      • 2016-02-02
      • 2015-03-24
      • 2011-05-18
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      相关资源
      最近更新 更多