Search code examples
angularjsapiangular-http-interceptors

incercept $http request to modify api call urls


var app = angular.module('app');
// register the interceptor as a service
app.factory('myHttpInterceptor', function($q ) {
    return {

        'request': function(config) {
            return config;
        }
    };
});

I am trying to modify the urls of api calls and append the api url to the start of the ajax calls in the interceptor insted of each service function like

    function getAssesmentResults(params) {

        return $http.get(url.api + '/results', {params: params})
            .then(function(response) {
                return response.data;
            });
    }

However the interceptor intercepts all http requests like .css or .html or .json files. What is a good way to modify the urls in the interceptor without modifying other http requests?


Solution

  • $http has a facility to intercept and rewrite URLs that is configured on the $httpProvider. When I run in production, I have an extra token: '/rest/' compared with development mode and I detect production mode ( prefix packing ) in the interceptor. This is in my app.js

    var rest_srvr = 'http://dev-pc.example.com:8000'
    app.factory('REST_Interceptor',[
            '$location',
    function($location) {
      var request = function(config) {
        if (RegExp('packing','i').test(window.location.host)) {
          return config
        }
        var rest_request_regex = new RegExp('^.*?/rest/(.*)$')
        //console.log('config.url=%s',config.url)
        config.url = config.url.replace(rest_request_regex,rest_srvr+'/$1')
    
        var files_request_regex = new RegExp('^/(files/(.*))$')
        config.url = config.url.replace(files_request_regex,rest_srvr+'/$1')
        //console.log('  is now config.url=%s',config.url)
        return config
      }
    
      var translate_subpath = function(subpath) {
        return request({url:'https://'+$location.host()+subpath}).url 
      }
    
      return {
        request: request,
        translate_subpath: translate_subpath
      }
    }])
    
    app.config([
              '$httpProvider','$cookiesProvider',
      function($httpProvider,  $cookiesProvider) {
        if (!RegExp('packing','i').test(window.location.host)) {
          $httpProvider.interceptors.push('REST_Interceptor')
        }
    }])