Billy Yang Billy Yang - 1 month ago 5
AngularJS Question

angularjs how to post key/values not json object

I hava a json object in my ctl:

$scope.disease


and anyone can edit it's properties and then post to server.

when save it,

$scope.save = function(){
$http.post('/***', $scope.disease)
}


however, the request body is as a json string.
while I want it to be as form data:

key1: value1
key2: value2
key3: value3


how can I do?

thanks a lot




after I set the Content-Type like this:

.config(['$httpProvider', function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}])


the request header:

Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type application/x-www-form-urlencoded; charset=UTF-8
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0


however the post parameter like this:

{"age":56,"birthday":"1958-07-14","familyHistory":"********************","id":1,"illness":"*********************","illnessHistory":"***************************","number":"21","selfDescription":"***********************"}


Because the $scope.disease is:

{
"age": 56,
"birthday": "1958-07-14",
"familyHistory": "********************",
"id": 1,
"illness": "*********************",
"illnessHistory": "***************************",
"number": "21",
"selfDescription": "***********************"
}


while the post parameter should like this:

"age": 56,
"birthday": "1958-07-14",
"familyHistory": "********************",
"id": 1,
"illness": "*********************",
"illnessHistory": "***************************",
"number": "21",
"selfDescription": "***********************"


Do you understand me?

Finally I add a transformRequest method to post-request:

$httpProvider.defaults.transformRequest=function(obj){
var str =[];
for(var p in obj){
str.push(encodeURICompent(p)+'='+encodeURICompent(obj[p]));
}
return str.join('&');
}


Then the problem solved!

Answer

In the $http.post call, add a correct Content-Type header to the config object (third parameter). If left empty, Angular defaults to a JSON payload.

headers : { 'Content-Type': 'application/x-www-form-urlencoded' }