设置XMLHttpRequest的代理以编辑表单数据 [英] Set proxy for XMLHttpRequest to edit form data

查看:122
本文介绍了设置XMLHttpRequest的代理以编辑表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编辑客户端的所有POST请求?我的研究表明应该可以使用代理对象关于XMLHttpRequest。如何检查POST请求并在将表单数据发送到服务器之前对其进行编辑?

How can I edit all POST requests from a client? My research says that it should be possible with a proxy object on XMLHttpRequest. How can I inspect a POST request and edit the form data before it gets sent to the server?

我已经尝试过这个方法,但发送的数据只是回复。

I've tried this approach but the data getting sent through is just responses.

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


推荐答案

这是一个重载XMLHttpRequest的IIFE原型方法,允许您拦截和修改正在发送的数据。我将由你来解决你的数据解析

Here's an IIFE that overloads XMLHttpRequest prototype methods that will allow you to intercept and modify data being sent. I'll leave it up to you to sort out parsing your data

(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>

这篇关于设置XMLHttpRequest的代理以编辑表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆