diff --git a/src/http-proxy-middleware.ts b/src/http-proxy-middleware.ts index e3012ec5..66fbf297 100644 --- a/src/http-proxy-middleware.ts +++ b/src/http-proxy-middleware.ts @@ -1,4 +1,5 @@ import * as express from 'express'; +import { ClientRequest } from 'http'; import * as httpProxy from 'http-proxy'; import * as _ from 'lodash'; import { createConfig } from './config-factory'; @@ -33,6 +34,9 @@ export class HttpProxyMiddleware { // log errors for debug purpose this.proxy.on('error', this.logError); + // fix proxied body if bodyParser is involved + this.proxy.on('proxyReq', this.fixBody); + // https://github.com/chimurai/http-proxy-middleware/issues/19 // expose function to upgrade externally (this.middleware as any).upgrade = (req, socket, head) => { @@ -174,4 +178,12 @@ export class HttpProxyMiddleware { this.logger.error(errorMessage, req.url, hostname, target, err.code || err, errReference); }; + + private fixBody = (proxyReq: ClientRequest, req: Request) => { + if (req.is('application/json')) { + const bodyData = JSON.stringify(req.body); + proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData)); + proxyReq.write(bodyData); + } + }; }