-
Notifications
You must be signed in to change notification settings - Fork 0
/
fix-request-body.js
33 lines (27 loc) · 1002 Bytes
/
fix-request-body.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// ref: https://github.com/chimurai/http-proxy-middleware/blob/2.x/src/handlers/fix-request-body.ts
import * as querystring from 'querystring';
/**
* Fix proxied body if bodyParser is involved.
*
* proxyReq: http.ClientRequest
*/
export function fixRequestBody(proxyReq, req) {
const requestBody = req.body;
if (!requestBody) {
return;
}
const contentType = proxyReq.getHeader('Content-Type');
const writeBody = (bodyData) => {
proxyReq.removeHeader('Content-Length');
// this automatically adds the transfer-encoding header which is incompatible with the content-length header
// The NSX load balancer was rejecting these requests with both headers present.
proxyReq.write(bodyData);
proxyReq.end();
};
if (contentType && contentType.includes('application/json')) {
writeBody(JSON.stringify(requestBody));
}
if (contentType && contentType.includes('application/x-www-form-urlencoded')) {
writeBody(querystring.stringify(requestBody));
}
}