0

I want to write a simple proxy which will save body of specific POST request to file.

I tried http-proxy but the problem is i do not know how to get request's body. There are headers and some other info, but no body in req object. Here is what i have at the moment. I inspected the logfile i create and do not see request body there.

var fs = require('fs'),
    http = require('http'),
    httpProxy = require('http-proxy');

var proxy = httpProxy.createProxyServer({});

var logger = function () {

    return function (request, response) {
        var logFile = fs.createWriteStream('./req' + new Date().getTime() + '.log');
        proxy.web(request, response, {target: 'http://localhost:8081'});

        var cache = [];
        logFile.write(
            JSON.stringify(request, function (key, value) {
                if (typeof value === 'object' && value !== null) {
                    if (cache.indexOf(value) !== -1) {
                        // Circular reference found, discard key
                        return;
                    }
                    // Store value in our collection
                    cache.push(value);
                }
                return value;
            }, 2)
        );
    }
};

var server = http.createServer(logger());
server.listen(8080);
Kirill
  • 6,762
  • 4
  • 51
  • 81

1 Answers1

1

Usually when I want to access request body with node I use the body-parser module.

How to use it !

mJehanno
  • 836
  • 1
  • 12
  • 19
  • Thank you. Works with json, but i have xml body and looks like bodyparser can't read it even if i set to `raw`. Any suggestions? – Kirill Oct 24 '16 at 15:40
  • this should do the job : [body-parser-xml](https://www.npmjs.com/package/body-parser-xml) – mJehanno Oct 24 '16 at 15:46
  • Sad that `body-parser` modifies original request by at least removing body from it :\ – Kirill Oct 27 '16 at 15:47