AngularJS - 如何将所有 jsons 请求放气和编码/解码为 base64?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14090619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:41:18  来源:igfitidea点击:

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

jsonhttpbase64angularjsdeflate

提问by Jakub Kuchar

Lets say i have several $resources and some $http around my angular application:

假设我的 angular 应用程序周围有几个 $resources 和一些 $http:

myApp.factory('Note', function($resource) {

  return $resource('http://', {id: '@id'}, 
    { 'index': { method: 'GET', isArray: true },
      'update': { method: 'PUT'},
    });
  });

with controller

带控制器

myApp.controller('NotesController',function NotesController($scope, Note, AuthenticationService) {

$scope.notes = Note.index({}, function(data){
    console.log('success, got data: ', data);
    $scope.response = "yoy!"
  }, function(err){
    console.log('error, got data: ', err);
    $scope.response = "yay!"
  }); 
});

and some request are made by $http directly like authentication

一些请求是由 $http 直接发出的,比如身份验证

var request = $http.post('http://', {email: email, password: password});

Where and How i can tell angular to deflate and encode/decode JSONs to base64 before the actual request is made / response is receive?

在发出实际请求/接收响应之前,我在哪里以及如何告诉 angular 压缩并将 JSON 编码/解码为 base64?

I quess i will wrap external libraries for deflate and encode/decode into factory. And then this factory will be injected somehere? Like $httpBackend ?

我问我会包装外部库用于放气和编码/解码到工厂。然后这个工厂会被注入到什么地方?像 $httpBackend ?

采纳答案by pkozlowski.opensource

You should have a look at the request / response transformersfor the $httpservice: http://docs.angularjs.org/api/ng.$http

您应该查看该服务的请求/响应转换$httphttp: //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.

要在本地覆盖这些转换,请将转换函数指定为配置对象的 transformRequest 和/或 transformResponse 属性。要全局覆盖默认转换,请覆盖 $httpProvider 的 $httpProvider.defaults.transformRequest 和 $httpProvider.defaults.transformResponse 属性。

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):

要定义全局请求/响应转换器,您可以沿着这些行编写代码(它更像是伪代码,不适用于所有浏览器,请参阅下面有关 Base64 的注释):

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/

当然,您的转换代码可能更复杂,并且取决于请求/响应标头,但总体思路就在这里。带有代码的 jsFiddle(检查控制台以查看请求是否已转换,您需要使用 Mozilla 或 WebKit 浏览器):http: //jsfiddle.net/Ydt5j/

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

对于从 / 到 Base64 的实际转换,请检查以下问题:如何在 JavaScript 中将字符串编码为 Base64?

回答by Jakub Kuchar

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)};
}]);

回答by Azizi Musa

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

这就是我在过滤器中所做的。item.htmlBody 包含带有 html 标签的 base64 编码文本

// 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)

好吧,我知道这并不能完全回答问题,但是通过一些小调整,您可以获得您想要的东西(针对未来遇到相同问题的人)