AngularJS,如何正确修改工厂中的http标头

时间:2014-10-07 02:42:38

标签: javascript angularjs factory

我希望Angular大师可以指出我正确的方向。使用以下格式的工厂时,如何修改POST的标题,以便:

'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'?

代码:

var tableModule = angular.module('theApp', ['ui-rangeSlider','ngScrollbar']);

tableModule.factory('Services', ['$http',
function($http) {
    return {
        get : function($path, callback) {
            return $http.get($path).success(callback);      
        },
        post : function($path, $data, callback) {
            return $http.post($path, $data).success(callback);
        }   
    };
}]);

2 个答案:

答案 0 :(得分:2)

我之前尝试过这样的事情。该方法看起来像

$scope.update = function (user) {
        $http({
            method: 'POST',
            url: 'https://mytestserver.com/that/does/not/exists',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            transformRequest: function (data) {
                var postData = [];
                for (var prop in data)
                postData.push(encodeURIComponent(prop) + "=" + encodeURIComponent(data[prop]));
                return postData.join("&");
            },
            data: user
        });
    }

另见我的小提琴http://jsfiddle.net/cmyworld/doLhmgL6/

答案 1 :(得分:2)

为什么不简单地将第三个 config 参数用于$http.post ...

post: function(path, data) {
    return $http.post(path, data, {
        headers: {
            'Content-type': 'application/x-www-form-urlencoded'
        }
    });
}