加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS – 如何对所有jsons请求进行deflate和编码/解码到base

发布时间:2020-12-17 07:27:35 所属栏目:安全 来源:网络整理
导读:让我说我的角度应用程序周围有几个$资源和一些$http: myApp.factory('Note',function($resource) { return $resource('http://',{id: '@id'},{ 'index': { method: 'GET',isArray: true },'update': { method: 'PUT'},}); }); 与控制器 myApp.controller('N
让我说我的角度应用程序周围有几个$资源和一些$http:
myApp.factory('Note',function($resource) {

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

与控制器

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,err);
    $scope.response = "yay!"
  }); 
});

并且一些请求由$http直接进行,如身份验证

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

在发出实际请求/接收响应之前,我可以在何处以及如何判断角度以对JSON进行收缩和编码/解码?

我想我将外部库包装为deflate并编码/解码到工厂.然后这个工厂将被注入?
喜欢$httpBackend?

您应该查看$http服务的请求/响应转换器: http://docs.angularjs.org/api/ng.$http

请求/响应转换器只是在将内容发送/返回给调用者之前可以调用的函数.您可以全局(针对所有请求/响应)以及每个请求基础指定转换函数:

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.

要定义全局请求/响应转换器,可以沿着这些行编写代码(它更像伪代码,不适用于所有浏览器,请参阅下面有关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));
    };

})

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

对于从/到Base64的实际转换,请检查此问题:How can you encode a string to Base64 in JavaScript?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读