Skip to content

fix: properly proxy the body #460

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/http-proxy-middleware.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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);
}
};
}