AngularJS - How to deflate and encode/decode to base64 all jsons request?

巧了我就是萌 提交于 2019-12-04 03:47:19
pkozlowski.opensource

You should have a look at the request / response transformers for the $http service: http://docs.angularjs.org/api/ng.$http

Request / response transformers are simply functions that can be invoked before content is sent / handed back to the caller. You can specify transforming functions globally (for all requests / responses) as well as per-request basis:

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.

To define global request / response transformers one would write the code along those lines (it is more like pseudo-code, won't work in all browsers, see notes about Base64 below):

angular.module('sample', [], function($httpProvider) {

    $httpProvider.defaults.transformRequest = function(data, headersGetter) {
        return btoa(JSON.stringify(data));
    };

    $httpProvider.defaults.transformResponse = function(data, headersGetter) {
        return JSON.parse(atob(data));
    };

})

Of course your transforming code could be more sophisticated and depend on request / response headers but the general idea is here. The jsFiddle with the code (check the console to see that a request gets transformed, you need to use Mozilla or a WebKit browser): http://jsfiddle.net/Ydt5j/

For the actual conversion from / to Base64 check this question: How can you encode a string to Base64 in JavaScript?

angular.module('services.base64',[]);
angular.module('services.base64').provider('base64', function () {

  this.encode = function(str) {
    return base64_encode(str);
  }

  this.decode = function(str) {
    return base64_decode(str);
  }

  this.$get = function() {
    return {};
  }

});

var myApp = angular.module('myApp',['services.base64'])

myApp.config(['base64Provider', function (base64Provider) {
    $httpProvider.defaults.transformRequest = function(request){return base64Provider.encode(request)};

    $httpProvider.defaults.transformResponse = function(response){return base64Provider.decode(response)};
}]);

this is how i do in filter. item.htmlBody contains base64 encoded text with html tag

// in template
<div ng-bind-html="item.htmlBody | decodeBase64">{{item.htmlBody}}</div>

//inside controller.js

.filter('decodeBase64', function(){
   return function(text){
   return atob(text);
   }
})

well, i know this doesnt exactly answer the question, but with some minor tweak, you can get what you want (targetting future person with the same problem)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!