3

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

danday74
  • 52,471
  • 49
  • 232
  • 283

2 Answers2

4

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.

Matteo Piazza
  • 2,462
  • 7
  • 29
  • 38
2

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()
})
danday74
  • 52,471
  • 49
  • 232
  • 283
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Fraser Mar 21 '18 at 09:48