-
Notifications
You must be signed in to change notification settings - Fork 869
/
Copy pathfix-request-body.ts
37 lines (30 loc) · 1 KB
/
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
34
35
36
37
import type * as http from 'http';
import type { Request } from '../types';
import * as querystring from 'querystring';
/**
* Fix proxied body if bodyParser is involved.
*/
export function fixRequestBody(proxyReq: http.ClientRequest, req: http.IncomingMessage): void {
// skip fixRequestBody() when req.readableLength not 0 (bodyParser failure)
if (req.readableLength !== 0) {
return;
}
const requestBody = (req as Request).body;
if (!requestBody) {
return;
}
const contentType = proxyReq.getHeader('Content-Type') as string;
if (!contentType) {
return;
}
const writeBody = (bodyData: string) => {
// deepcode ignore ContentLengthInCode: bodyParser fix
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
};
if (contentType.includes('application/json')) {
writeBody(JSON.stringify(requestBody));
} else if (contentType.includes('application/x-www-form-urlencoded')) {
writeBody(querystring.stringify(requestBody));
}
}