Log request/responses bodies with http-proxy-middleware
Asked Answered
P

2

12

I'm using http-proxy-middleware to implement a transparent proxy.

I'd like to do request/response inspection. I mean, I'd like to print in a text file request/responses that go through the proxy whithout do any modifying on them.

Up to now, what I'm using is something like that (simplified version):

app.use('/proxy/:service/', proxy({
        pathRewrite: function(path, req){
            ...
        },
        router: function(req) {
            ...
        },
        onProxyRes: function(proxyRes, req, res) {
            log("Req URL: " + req.originalUrl);
            log("Response status code: " + proxyRes.statusCode);
        }
}));

(log() is a helper function that uses a string as input and prints it is my log file)

Thus, basically I'm using onProxyRes to intercept the response and do logging at that point. The problem is that I have been only able to make it work for things like URL, status code, headers, etc. but I haven't find the payload body in req and/or resProxy objects.

I have read about how to get the res body here. However, it seems to be complex solution (needs to set a data event handler). And it doesn't cover the req body, as far as I understand.

Any hint/help/reference is hightly appreciated, please. Not sure if even using onProxyRes is the best way of implementing this, maybe the library provides some functionality to cover the request/response case.

Physicochemical answered 11/5, 2018 at 14:41 Comment(0)
M
1

If you use latest express version, this will work.

app.use(express.json())
app.use('/proxy/:service/', proxy({
        onProxyRes: function(proxyRes, req, res) {
            log("Req URL: " + req.originalUrl);
            log("Response status code: " + proxyRes.statusCode);
        }
}));
Meadowlark answered 28/10, 2021 at 16:4 Comment(0)
X
0

If you want the req.body, you have to use a library to get it (or build it out of the stream yourself). I recommend body-parser

Xenos answered 11/5, 2018 at 14:54 Comment(1)
Thank you for the feedback! I have had a look to the link to body-parser, but the way of using it in onProxyRes is not straighforward to me... Do you have any sample code or link, please?Physicochemical

© 2022 - 2024 — McMap. All rights reserved.