如何跳过HTTP请求的angularjs拦截器?

时间:2016-06-06 03:48:18

标签: angularjs interceptor angularjs-http

我有一个angularjs应用程序,其中有一个拦截器,可以将授权令牌添加到每个请求的标头中。

但是,我需要使用的应用程序中的某个地方以及拦截器对其进行破坏的外部API,因为它添加了此外部API提供程序无法接受的授权标头。我怎样才能使angularjs HTTP跳过拦截器,只针对这个特定情况?

拦截器代码如下:

app.factory('authInterceptorService', ['$q', '$injector', '$location', 'localStorageService', function ($q, $injector, $location, localStorageService) {
    var authInterceptorServiceFactory = {};
    var $http;

    var _request = function (config) {

        config.headers = config.headers || {};

        var authData = localStorageService.get('authorizationData');
        if (authData) {
            //console.log("token: " + authData.token.substring(0, 10));
            //console.log("user: " + authData.userName);
            config.headers.Authorization = 'Bearer ' + authData.token;
        }
        return config;
    }

    var _responseError = function (rejection) {
        var deferred = $q.defer();
        if (rejection.status === 401) {
            var authService = $injector.get('authService');
            authService.refreshToken().then(function (response) {
                _retryHttpRequest(rejection.config, deferred);
            }, function () {
                authService.logOut();
                $location.path('/login');
                deferred.reject(rejection);
            });
        } else {
            deferred.reject(rejection);
        }
        return deferred.promise;
    }

    var _retryHttpRequest = function (config, deferred) {
        console.log('retrying');
        $http = $http || $injector.get('$http');
        $http(config).then(function (response) {
            deferred.resolve(response);
            //console.log("success:" +response);
        }, function (response) {
            deferred.reject(response);
            //console.log("error:" + response);
        });
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}]);

4 个答案:

答案 0 :(得分:9)

轻松

$http.get("url" , {noAuth : true}).then(success(),error());

在拦截器

  var _request = function (config) {

    config.headers = config.headers || {};

    var authData = localStorageService.get('authorizationData');
    if (authData && !config.noAuth) {
        //console.log("token: " + authData.token.substring(0, 10));
        //console.log("user: " + authData.userName);
        config.headers.Authorization = 'Bearer ' + authData.token;
    }
    return config;
}

答案 1 :(得分:6)

这样写: -

   var _request = function (config) {
    if (config.url.indexOf('yourExternalApiUrl') > -1) {
         return config;
    } else {
         config.headers = config.headers || {};
         var authData = localStorageService.get('authorizationData');
         if (authData) {
             //console.log("token: " + authData.token.substring(0, 10));
             //console.log("user: " + authData.userName);
             config.headers.Authorization = 'Bearer ' + authData.token;
         }
    return config;
    }        
}

有关详细信息,请参阅:http://www.codemosquitoes.com/2016/06/using-angularjs-interceptors-with-http.html

答案 2 :(得分:4)

简单。改变这一行

if (authData) {

if (authData && !config.headers.hasOwnProperty('Authorization')) {

对于您不希望应用标头的任何请求,请使用

$http({
    headers { Authorization: null },
    // and the rest
})

答案 3 :(得分:1)

如果您正在寻找auth0拦截器:

export class InterceptorService implements HttpInterceptor {
    constructor(private auth: AuthService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        var allow = ['/assets/i18n/de.json', '/assets/i18n/en.json'];

        if (allow.includes(req.url)) {
            const noToken = req.clone();
            return next.handle(noToken);
        }
        return this.auth.getTokenSilently$().pipe(
            mergeMap(token => {
                const tokenReq = req.clone({
                    setHeaders: { Authorization: `Bearer ${token}` }
                });
                return next.handle(tokenReq);
            }),
            catchError(err => throwError(err))
        );
    }
}