Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: decorating $http

I have a simple controller, like:

function MyController($scope, $http) {
    ...
    $http.post(url).success(function(data) {
            console.log(data)
         });
}
MyController.$inject = ['$scope', '$http'];

Everything works as expected, but I have a problem. The returning JSON is commented with /** */ for security reasons. With jQuery I have extended the $.ajax object to remove this comments and then parse the result. I would like to achieve the same with AngularJS and somehow tell $http to remove the comments from each response too. I want to do this for my whole application and avoid typing always the same.

Any ideas how I can do that?

like image 494
Christian Avatar asked Jul 31 '12 12:07

Christian


2 Answers

You're going to want to transform all your $http responses. I haven't done this before, but the relevant documentation is below.

Transforming Requests and Responses

Both requests and responses can be transformed using transform functions. By default, Angular applies these transformations:

Request transformations:

  • if the data property of the request config object contains an object, serialize it into JSON format.

Response transformations:

  • if XSRF prefix is detected, strip it (see Security Considerations section below)
  • if json response is detected, deserialize it using a JSON parser

To override these transformation locally, specify transform functions as transformRequest and/or transformResponse properties of the config object. To globally override the default transforms, override the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties of the $httpProvider.

Read more in the $http service documentation.

like image 63
Noah Freitas Avatar answered Oct 15 '22 02:10

Noah Freitas


You may wish to switch from wrapping your JSON responses in /** */ to that which is already supported out of the box by $http. Instead, prefix your JSON responses with )]}',\n.

e.g. If your JSON response is:

['one','two']

then, instead of returning:

/**['one','two']*/

simply return:

)]}',
['one','two']

For details, see the JSON Vulnerability Protection section in http://docs.angularjs.org/api/ng.$http.

like image 22
Fred Sauer Avatar answered Oct 15 '22 02:10

Fred Sauer