首页 > 解决方案 > 为 XMLHttpRequest 设置代理以编辑表单数据

问题描述

如何编辑来自客户端的所有 POST 请求?我的研究表明,在 XMLHttpRequest 上使用代理对象应该是可能的。如何在发送到服务器之前检查 POST 请求并编辑表单数据?

我已经尝试过这种方法,但发送的数据只是响应。

var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
    var xhr = new _XMLHttpRequest();

    // augment/wrap/modify here
    var _open = xhr.open;
    xhr.open = function() {
        // custom stuff
        return _open.apply(this, arguments);
    }

    return xhr;
}

标签: javascriptgoogle-chrome

解决方案


这是一个重载 XMLHttpRequest 原型方法的 IIFE,它允许您拦截和修改正在发送的数据。我会留给你来整理解析你的数据

(function(xhr) {
  var
    proto = xhr.prototype,
    _send = proto.send,
    _open = proto.open;
  
  // overload open() to access url and request method
  proto.open = function() {
    // store type and url to use in other methods
    this._method = arguments[0];
    this._url = arguments[1];
    _open.apply(this, arguments);
  }
  
  // overload send to intercept data and modify
  proto.send = function() {
   // using properties stored in open()
    if (this._method.toLowerCase() === 'post') {
      console.log('USERS DATA :: ', arguments[0]);
      console.log('URL :: ', this._url);
      
      // modify data to send
      arguments[0] = 'item=beer&id=3';
    }
    _send.apply(this, arguments);
  }

})(XMLHttpRequest);

// use jQuery ajax to demonstrate
$.post('http://httpbin.org/post', { item: 'test',  id: 2})
      .then(data => console.log('RESPONSE ::', data.form))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


推荐阅读