21

Let's set up a simple example:

$scope.whatDoesTheFoxSay = function(){
    $http.post("/backend/ancientMystery", {
...

How can I globally transform the URL where the post request is sent to? Essentially I want to prepend an URL to every http request.

What I have tried is setting a variable in the $rootScope containing the url when the application starts. But this is not what I want my code to look like:

$scope.whatDoesTheFoxSay = function(){
    $http.post($rootScope.backendUrl + "/backend/hidingDeepInTheWoods", {
...

Am I correct assuming that I should look into $httpProvider.defaults.transformRequest? Can anyone provide me with some basic example code?

3 Answers 3

42

I have another approach of using request interceptor with $http which will handle all the url's at one common place

<!doctype html>
<html ng-app="test">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>

  </head>
 <body ng-controller="test" >    


<!-- tabs -->


 <script>
     var app = angular.module('test', []);
     app.config(function ($httpProvider) {
         $httpProvider.interceptors.push(function ($q) {
             return {
                 'request': function (config) {
                     config.url = config.url + '?id=123';
                     return config || $q.when(config);

                 }

             }
         });
     });

     app.controller('test', function ($scope,$http) {
         $http.get('Response.txt').success(function (data) { alert(data) }).error(function (fail) {

         });
     });

   </script>
</body>


</html>
Sign up to request clarification or add additional context in comments.

2 Comments

When using this along with ngToast I get the error Error: [$compile:tplrt] Template for directive 'toast' must have exactly one root element
config.url = config.url + '?id=123'; return config || $q.when(config); Right after accessing config.url, what would make config evaluate to false?
0

Ran into this problem of "cache-busting in AngularJS" and wanted to share a working solution that also includes an option to 'un-cache' $templatecache resources.

This solution correctly returns a value and not a promise ;) and doesn't form malformed URL's if your request already contains $_GET values.

var __version_number = 6.0; // Date.now('U'); // 'U' -> linux/unix epoch date int

app.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push(function () {
    return {
      'request': function (config) {
        // !!config.cached represents if the request is resolved using 
        //      the angular-templatecache
        if (!config.cached) {
          config.url += ( (config.url.indexOf('?') > -1) ? '&' : '?' ) 
            + config.paramSerializer({v: __version_number});
        } else if (config.url.indexOf('no-cache') > -1) {
          // if the cached URL contains 'no-cache' then remove it from the cache
          config.cache.remove(config.url);
          config.cached = false; // unknown consequences
          // Warning: if you remove the value form the cache, and the asset is not
          //          accessable at the given URL, you will get a 404 error.
        }
        return config;
      }
    }
  });
}]);

Comments

0

A modern day approach would be to implement a custom Http client.

export function getCustomHttp(xhrBackend: XHRBackend, requestOptions: RequestOptions) {
    return new CustomHttp(xhrBackend, requestOptions);
}

export class CustomHttp extends Http {
    public constructor(backend: XHRBackend, private defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    public request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        url = 'https://www.customURL.com/' + url; // Of course, you'd pull this from a config
        return super.request(url, options);
    }
}

Then you would simply modify your app.module as follows:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoute,
    RouterModule
  ],
  providers: [
    HttpModule,
    {
      provide: Http,
      useFactory: getCustomHttp,
      deps: [XHRBackend, RequestOptions]
    }
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.