programing

각도 사용법특정 HTTP 요청만 가로채는 JS 인터셉터?

golfzon 2023. 3. 25. 12:05
반응형

각도 사용법특정 HTTP 요청만 가로채는 JS 인터셉터?

모든 요청을 대행 수신하는 방법은 알고 있지만 리소스 요청만 대행 수신합니다.

이거 할 줄 아는 사람 있어요?

services.config(['$httpProvider',function($httpProvider) {
    $httpProvider.interceptors.push('myHttpInterceptor');
}]);

services.factory("userPurchased", function ($resource) {
    return $resource("/api/user/purchases/:action/:item", 
        {}, 
        {
            'list': {method: 'GET', params: {action: 'list'}, isArray: false},
            'save': {method: 'PUT', params: {item: '@item'}},
            'remove': {method: 'DELETE', params: {item: '@item'}},
        }
    );
});

services.factory('myHttpInterceptor', function($q,$rootScope) {
    // $rootScope.showSpinner = false;
    return {

      response: function(response) {
        $rootScope.showSpinner = false;
        // do something on success
        console.log('success');
        console.log('status', response.status);
        //return response;
        return response || $q.when(response);
      },

     responseError: function(response) {
        // do something on error
        $rootScope.showSpinner = true;
        console.log('failure');
        console.log('status', response.status)
        //return response;
        return $q.reject(response);
      }
    };
  });

특정 리소스의 요청만 대행 수신하려면 옵션인interceptor의 특성$request액션.Angular의 매뉴얼은 이쪽(사용방법>액션)을 참조해 주세요.

자바스크립트

angular.module('app', ['ngResource']).
  factory('resourceInterceptor', function() {
    return {
      response: function(response) {
        console.log('response intercepted: ', response);
      }
    }
  }).
  factory('resourceService', ['$resource', 'resourceInterceptor', function($resource, resourceInterceptor) {
    return $resource(":name", 
        {}, 
        {
            'list': {method: 'GET', isArray: false, interceptor: resourceInterceptor}
        }
    );
  }]).
  run(['resourceService', '$http', function(resourceService, $http) {
    resourceService.list({name: 'list.json'}); // <= intercepted
    $http.get('list.json'); // <= not intercepted
  }]);

Pluker: http://plnkr.co/edit/xjJH1rdJyB6vvpDACJOT?p=preview

응답 핸들러에서 원하는 요청을 필터링하는 방법밖에 없습니다.

예.

...
response: function(response) {
    if(response.config.url.startsWith('/api/')) {
        //Do your custom processing here
    }

    return response;
}
...

string.startsWith()의 폴리필

//Taken from http://stackoverflow.com/questions/646628/javascript-startswith
if (typeof(String.prototype.startsWith) === 'undefined') {
    String.prototype.startsWith = function(str) {
        return this.slice(0, str.length) === str;
    };
}

권장되는 방법은 "매직" 인증 헤더를 현재 OAuth 토큰으로 대체하는 HTTP 대행 수신기를 사용하는 것입니다.아래 코드는 OAuth에 따라 다르지만, 이 문제를 해결하는 것은 독자에게 간단한 연습입니다.

// Injects an HTTP interceptor that replaces a "Bearer" authorization header
// with the current Bearer token.
module.factory('oauthHttpInterceptor', function (OAuth) {
  return {
    request: function (config) {
      if (config.headers.Authorization === 'Bearer') {
        config.headers.Authorization = 'Bearer ' + btoa(OAuth.accessToken);
      }
      return config;
    }
  };
});

module.config(function ($httpProvider) {
  $httpProvider.interceptors.push('oauthHttpInterceptor');
});
/**object single interceptor**/ 
 function SingleCallInterceptor(callbacks){

    this.receive=function(response) {

      switch (response.status) {

        case 200:

          callbacks.success(apiResponse);

          break;

        default :

          callbacks.error(response);
      }

    }

  }


var successfn=function(response){  //i have my response}

var errorfn=function(response){  //i have my error}

var responseInterceptor=new SingleCallInterceptor({success:successfn,error:errorfn});

        $http({

        url: "www.itsdirtysolutioniknow.it,

        method: "GET",

        dataType: "JSONP",

      }).then(responseInterceptor.receive,responseInterceptor.receive);

기본적으로는 angular는 애플리케이션/json 헤더를 송수신합니다.이는 다음과 같은 HTTP 응답 헤더에서 얻을 수 있습니다.

services.config(['$httpProvider',function($httpProvider) {
    $httpProvider.interceptors.push('myHttpInterceptor');
}]);

services.factory("userPurchased", function ($resource) {
    return $resource("/api/user/purchases/:action/:item", 
        {}, 
        {
            'list': {method: 'GET', params: {action: 'list'}, isArray: false},
            'save': {method: 'PUT', params: {item: '@item'}},
            'remove': {method: 'DELETE', params: {item: '@item'}},
        }
    );
});

services.factory('myHttpInterceptor', function($q,$rootScope) {
    // $rootScope.showSpinner = false;
    return {

      response: function(response) {
        // use this line to if you are receiving json, else use xml or any other type
        var isJson = response.config.headers.Accept.indexOf('json')>-1;
        $rootScope.showSpinner = false;
        // do something on success
        console.log('success');
        console.log('status', response.status);
        //return response;
        return response || $q.when(response);
      },

     responseError: function(response) {
        // use this line to if you are receiving json, else use xml or any other type
        var isJson = response.config.headers.Accept.indexOf('json')>-1;
        // do something on error
        $rootScope.showSpinner = true;
        console.log('failure');
        console.log('status', response.status)
        //return response;
        return $q.reject(response);
      }
    };
  });

방금 전에 우연히 구글라피스가 또 다른 문제를 발견했는데Authorization서버에서 사용하는 JWT가 (분명히) 서버에 유효하지 않기 때문에 401 응답을 던졌고, 내 코드는 자동으로 토큰을 제거하고 사용자를 로그인 페이지로 리디렉션하도록 설정되었습니다.(어떤 401 응답이라도 사용자가 로그아웃되기 때문에 매우 잘 작성되지 않았습니다).

저는 방금 이 해결책을 생각해 냈습니다.request요격기에서의 방법은 꽤 잘 작동한다고 생각합니다.

.service('authInterceptor', ["$q", "$location", "tokenService", function($q, $location, tokenService){
    this.request = function(config) {
//        console.log($location.host());
        var token = tokenService.getToken();
        if(token && config.url.indexOf($location.host()) > -1) {
            config.headers = config.headers || {};
            config.headers.Authorization = "Bearer " + token
        }
        return config
    }

    this.responseError = function(response) {
//        console.log(response.config.url)
        if (response.status === 401) {
            tokenService.removeToken();
            $location.path('/login')
        }
        return $q.reject(response);
    }
}])

request로컬 스토리지에 토큰이 있는지 여부 및 요청 URL이 동일한 호스트(에서 가져온)에 작성되었는지 확인합니다.$location.host())를 참조해 주세요.이것은 localhost 및 사이트를 전개하게 되는 URL에 대해 기능합니다.

테스트도 별로 하지 않았기 때문에, 혹시라도 결점이 발견되면 가르쳐 주세요.

오래된 질문인 것은 알지만 여러 $http 대행 수신기를 푸시하여 계속 작동하기를 원하는 경우, 대행 수신 체인이 계속 작동하도록 답변을 반환하십시오.

    module.factory('resourceInterceptor', ['$q', function($q) {
        return {
            response: function(response) {
                // do your conditional logic here
                if (...) {
                    return $q.resolve(response);
                }
            },
            responseError: function(response) {
                // do your conditional logic here   
                if (...) {
                    return $q.reject(response);
                }
            }
        };
    }]);

언급URL : https://stackoverflow.com/questions/23021416/how-to-use-angularjs-interceptor-to-only-intercept-specific-http-requests

반응형