AngularJS: decoration $ http

I have a simple controller, for example:

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 out / ** * / for security reasons. With jQuery, I extended the $ .ajax object to remove these comments and then parse the result. I would like to achieve the same with AngularJS and somehow say $ http to remove comments from each answer. I want to do this for my entire application and not always type the same thing.

Any ideas how I can do this?

+6
source share
2 answers

You will want to convert all your responses to $http . I have not done this before, but the relevant documentation is below.

Request and Response Conversion

Both requests and responses can be converted using function conversion. By default, Angular applies the following transformations:

Request Conversions:

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

Response Conversions:

  • if an XSRF prefix is ​​found, separate it (see the security considerations section below)
  • If a json response is found, deserialize it using the JSON Parser

To override these transforms locally, specify the transform functions as the transformRequest and / or transformResponse properties of the configuration object. To globally override the default value of converts, overrides the $ httpProvider.defaults.transformRequest and $ httpProvider.defaults.transformResponse properties of the $ HttpProvider.

Read more in the $http service documentation .

+7
source

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

eg. If your answer is JSON:

 ['one','two'] 

then instead of returning:

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

just return:

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

For more information, see Protecting JSON Vulnerabilities at http://docs.angularjs.org/api/ng.$http .

+3
source

Source: https://habr.com/ru/post/921768/


All Articles