Set proxy for XMLHttpRequest to edit form data

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

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

回答1:

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>


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