Form URL encoded post with AngularJS
20/Dec 2012
The AngularJS framework is amazing in many things but I had a hell of a time trying to get the $http.post function to encode and send my object correctly. The first thing you should do is set the content type, either globally like this
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.post('/foo/bar', postData,headers:{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}).success(function(responseData) { /*do stuff with response*/ });
A hack around this problem is to just have a single post item and then serialize the object to that value and then just unserialze from that item to the object on the server like this:
$http.post('/foo/bar', 'data='+$filter('json')(postData))
.success(function(data) {
//do stuff with response
});
There are two problems with approach it is difficult to sanitize on the server and it is just not the right way to do it. I then wrote this function to transform the data:
function formEncode(obj) {
var encodedString = '';
for (var key in obj) {
if (encodedString.length !== 0) {
encodedString += '&';
}
encodedString += key + '=' + encodeURIComponent(obj[key]);
}
return encodedString.replace(/%20/g, '+');
}
$http.post('/foo/bar', formEncode(postData))
.success(function(data) {
//do stuff with response
});
It needs some further refinement but I just refuse to include JQuery just to use the $.param() function. I also feel much more comfortable with this than some of the other hacks that I saw while trying to solve this problem.