Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack config proxy request body logging

Webpack dev server proxy config documentation seen here:

https://webpack.js.org/configuration/dev-server/#devserver-proxy

says it uses http-proxy-middleware:

https://github.com/chimurai/http-proxy-middleware#http-proxy-events

Using the onProxyRes function documented in the above link I do the following:

function onProxyRes(proxyRes, req, res) {
    proxyRes.headers['x-added'] = 'foobar';     // add new header to response
    delete proxyRes.headers['x-removed'];       // remove header from response
    console.log(req.headers)                    // log headers
    console.log(req.body)                  // undefined
    console.log(proxyReq.body)             // undefined
}

My problem, although everything else works great - I cannot log the Request Body - it returns undefined

Anyone know how to read the request body for debugging purposes? Do I somehow need to use the npm body-parser module? If so, how? thx

like image 635
danday74 Avatar asked Dec 31 '25 13:12

danday74


2 Answers

I solved a similar problem using body-parser.

I was trying to modify the request body before sending it to server, and it caused the request to hang maybe because, altering the body, the Content-Length of the request was no more matching (causing it to be truncated).

The solution was "resizing" Content-Length before writing the new request body:

var bodyParser = require('body-parser');   

devServer: {
    before: function (app, server) {
        app.use(bodyParser.json());
    },
    onProxyReq: function (proxyReq, req, res) {
        req.body = {
            ...req.body,
            myProperty: "myPropertyValue"
        };

        const body = JSON.stringify(req.body);

        proxyReq.setHeader('Content-Length', Buffer.byteLength(body));

        proxyReq.write(body);
    }
}

Not sure, but in your case it could be that the request has been truncated by adding/removing headers, causing it to hang.

like image 114
Matteo Piazza Avatar answered Jan 03 '26 09:01

Matteo Piazza


I tried logging the request with the express body-parser module but it caused the requests to hang. Using the body module to log the request body fixed it.

const anyBody = require('body/any')
onProxyReq(proxyReq, req, res) {
    anyBody(req, res, function (err, body) {
        if (err) console.error(err)
        console.log(body)
    })
})

Note that I also used this same approach inside express as follows:

app.use((req, res, next) => {
    anyBody(req, res, function (err, body) {
        if (err) console.error(err)
        console.log(body)
    })
    next()
})
like image 42
danday74 Avatar answered Jan 03 '26 09:01

danday74



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!