AngularJs http方法覆盖PUT-POST

时间:2013-09-27 13:46:57

标签: angularjs http-method x-http-method-override

有没有办法使用角色的$resource服务使用请求中的X-HTTP-Method-Override_method参数进行http方法覆盖?

2 个答案:

答案 0 :(得分:2)

在资源工厂中,您可以为每种类型的请求指定方法。

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

是标准方法,但您也可以使用它:

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

答案 1 :(得分:1)

如果其他人正在寻找代码段,请访问:

(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'));