thoughts . experiments . code

Decorate AngularJS $http Service to Convert PUT, DELETE Requests to POST

Below is the code for AngularJS 1.0.x to convert PUT and DELETE requests to ‘POST’ over the network, but use them as they were. AngularJS 1.0.x has Responses Interceptors but no Request Interceptors (available from 1.1.x). So, I came with this code and of course it’s not pretty :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/** AngularJS $http service decorator to convert PUT, DELETE as POST */
var App = angular.module('App');
App.config(['$provide', function($provide) {
  
  // configure http provider to convert 'PUT', 'DELETE' methods to 'POST' requests
  $provide.decorator('$http', ['$delegate', function($http) {
      // create function which overrides $http function
      var httpStub = function (method) {
          return function(url, data, config) {
              // AngularJS $http.delete takes 2nd argument as 'config' object
              // 'data' will come as 'config.data'
              if(method === 'delete') {
                  config = data;
                  config && (data = config.data);
              }
              
              config || (config = {});
              config.headers || (config.headers = {});
              
              // override actual request method with 'POST' request
              config.method = 'POST';
              
              // set the actual method in the header
              config.headers['X-HTTP-Method-Override'] = method;
              
              return $http(angular.extend(config, {
                  url: url,
                  data: data
              }));
          };
      };
      
      // backup of original methods
      $http._put = $http.put;
      $http._delete = $http['delete'];
      
      // override the 
      $http.put = httpStub('put');
      $http['delete'] = httpStub('delete');
      
      return $http;
  }]);
  
}]);

Why is it required?

I use REST (JAX-RS) approach for developing & exposing server side services are resources in almost all projects and I totally recommend it.