简体   繁体   中英

Capture ajax request and its POST data

I want to capture an ajax request and its POST-data but haven't found any way of doing it.

I've been trying with: XMLHttpRequest.prototype.open but haven't found any way of capturing the POST data using it.

I suppose this is what I'd like to do:

(function(open) {
    XMLHttpRequest.prototype.open = function (method, url, async) {
        this.addEventListener('readystatechange', function () {
            if(url.indexOf("the-url-i-want-to-capture") !== -1 && this.readyState === 4 && this.status === 200) {
                // do ... something ... with the POST data
            }
        }, false);
        open.call(this, method, url, async);
    };
})(XMLHttpRequest.prototype.open);

When you are working with native ajax XMLHttpRequest object, do not use prototype to access open , but first declare the variable and then use all the methods that it offers, like open , send etc.

Also note that you can't intercept and capture data because FormData objects are not stringifiable objects (hint: images?). only if you are using GET method you can see data in the url .

I've added example for you to see response from POST request

See this page to get you started with all the details: https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started

 (function(open) { // declare new http client var req = new XMLHttpRequest(); // define what to do after req finishes req.onreadystatechange = function(){ if(req.readyState === XMLHttpRequest.DONE) console.log( req.responseText ); }; // start our POST req req.open('POST', 'https://jsonplaceholder.typicode.com/posts?test', true); // sent it req.send(); })(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM