-
Notifications
You must be signed in to change notification settings - Fork 869
/
Copy pathfix-request-body.ts
33 lines (27 loc) · 1002 Bytes
/
fix-request-body.ts
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
import type * as http from 'http';
import * as querystring from 'querystring';
export type BodyParserLikeRequest = http.IncomingMessage & { body: any };
/**
* Fix proxied body if bodyParser is involved.
*/
export function fixRequestBody<TReq = http.IncomingMessage>(
proxyReq: http.ClientRequest,
req: TReq,
): void {
const requestBody = (req as unknown as BodyParserLikeRequest).body;
if (!requestBody) {
return;
}
const contentType = proxyReq.getHeader('Content-Type') as string;
const writeBody = (bodyData: string) => {
// deepcode ignore ContentLengthInCode: bodyParser fix
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
};
if (contentType && (contentType.includes('application/json') || contentType.includes('+json'))) {
writeBody(JSON.stringify(requestBody));
}
if (contentType && contentType.includes('application/x-www-form-urlencoded')) {
writeBody(querystring.stringify(requestBody));
}
}