Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs http method override PUT-POST

IS there a way to do the http method override with angular's $resource service using the X-HTTP-Method-Override or a _method param in the request?

like image 965
rascio Avatar asked Mar 25 '26 14:03

rascio


2 Answers

In your Resource factory you can specify the method for each type of request.

angular.module('myServices', ['ngResource'])
.factory('Customer', function($resource){
        return $resource('../api/index.php/customers/:id', {id:'@id'}, {
            update: {method:'PUT'}
        });
    })

is the standard method, but you could use this too:

angular.module('myServices', ['ngResource'])
.factory('Customer', function($resource){
        return $resource('../api/index.php/customers/:id', {id:'@id'}, {
            update: {params: {'_method':'PUT', id: '@id'}}
        });
    })
like image 51
CubCouper Avatar answered Mar 27 '26 10:03

CubCouper


In case someone else is looking for a code snippet, here it is:

(function(module) {
    function httpMethodOverride($q) {
        var overriddenMethods = new RegExp('patch|put|delete', 'i');

        return {
            request: function(config) {
                if (overriddenMethods.test(config.method)) {
                    config.headers = config.headers || {};
                    config.headers['X-HTTP-Method-Override'] = config.method;
                    config.method = 'POST';
                }

                return config || $q.when(config);
            }
        };
    }

    module.factory('httpMethodOverride', httpMethodOverride);
    module.config(function($httpProvider) {
        $httpProvider.interceptors.push('httpMethodOverride');
    });
})(angular.module('app-module'));
like image 39
Darlan Alves Avatar answered Mar 27 '26 09:03

Darlan Alves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!