AngularJS applies some basic transformations on all requests and responses made through its $http service. These include:
Request transformations
If the data property of the requested config object contains an object, serialize it into JSON format.
Response transformations
If an XSRF prefix is detected, strip it. If a JSON response is detected, deserialize it using a JSON parser.
If you don’t want some of the transformations, or want to add your own, then you can pass in your functions as part of the config. These functions get the HTTP request/response body, as well as the headers, and respond with the serialized, modified version.
Set these config functions using the transformRequest and transformResponse keys, which are configured using the $httpProvider service in the config function of the module.
When to Use
When would we use these? Let us assume that we have a server which is more attuned to the jQuery way of doing things. It would expect our POST data to come in the form key1=val1&key2=val2 (that is, a string), instead of the JSON form of {key1: val1, key2: val2}. While we could make this change at every request, or add a transform Request call individually, for the purpose of this example, we are going to add a general transformRequest, so that for all outgoing calls, this transformation from JSON form to a string happens. Here’s how we would do this:
snippet
var module = angular.module('myApp');
module.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(data) {
// We are using jQuery’s param method to convert our
// JSON data into the string form
return $.param(data);
};
});