File tree 2 files changed +25
-8
lines changed
2 files changed +25
-8
lines changed Original file line number Diff line number Diff line change @@ -17,21 +17,23 @@ export function fixRequestBody<TReq = http.IncomingMessage>(
17
17
}
18
18
19
19
const contentType = proxyReq . getHeader ( 'Content-Type' ) as string ;
20
+
21
+ if ( ! contentType ) {
22
+ return ;
23
+ }
24
+
20
25
const writeBody = ( bodyData : string ) => {
21
- // deepcode ignore ContentLengthInCode: bodyParser fix
22
26
proxyReq . setHeader ( 'Content-Length' , Buffer . byteLength ( bodyData ) ) ;
23
27
proxyReq . write ( bodyData ) ;
24
28
} ;
25
29
26
- if ( contentType && ( contentType . includes ( 'application/json' ) || contentType . includes ( '+json' ) ) ) {
30
+ // Use if-elseif to prevent multiple writeBody/setHeader calls:
31
+ // Error: "Cannot set headers after they are sent to the client"
32
+ if ( contentType . includes ( 'application/json' ) || contentType . includes ( '+json' ) ) {
27
33
writeBody ( JSON . stringify ( requestBody ) ) ;
28
- }
29
-
30
- if ( contentType && contentType . includes ( 'application/x-www-form-urlencoded' ) ) {
34
+ } else if ( contentType . includes ( 'application/x-www-form-urlencoded' ) ) {
31
35
writeBody ( querystring . stringify ( requestBody ) ) ;
32
- }
33
-
34
- if ( contentType && contentType . includes ( 'multipart/form-data' ) ) {
36
+ } else if ( contentType . includes ( 'multipart/form-data' ) ) {
35
37
writeBody ( handlerFormDataBodyData ( contentType , requestBody ) ) ;
36
38
}
37
39
}
Original file line number Diff line number Diff line change @@ -154,4 +154,19 @@ describe('fixRequestBody', () => {
154
154
expect ( proxyRequest . setHeader ) . toHaveBeenCalledWith ( 'Content-Length' , expectedBody . length ) ;
155
155
expect ( proxyRequest . write ) . toHaveBeenCalledWith ( expectedBody ) ;
156
156
} ) ;
157
+
158
+ it ( 'should parse json and call write() once with incorrect content-type application/x-www-form-urlencoded+json' , ( ) => {
159
+ const proxyRequest = fakeProxyRequest ( ) ;
160
+ proxyRequest . setHeader ( 'content-type' , 'application/x-www-form-urlencoded+json' ) ;
161
+
162
+ jest . spyOn ( proxyRequest , 'setHeader' ) ;
163
+ jest . spyOn ( proxyRequest , 'write' ) ;
164
+
165
+ fixRequestBody ( proxyRequest , createRequestWithBody ( { someField : 'some value' } ) ) ;
166
+
167
+ const expectedBody = JSON . stringify ( { someField : 'some value' } ) ;
168
+ expect ( proxyRequest . setHeader ) . toHaveBeenCalledWith ( 'Content-Length' , expectedBody . length ) ;
169
+ expect ( proxyRequest . write ) . toHaveBeenCalledTimes ( 1 ) ;
170
+ expect ( proxyRequest . write ) . toHaveBeenCalledWith ( expectedBody ) ;
171
+ } ) ;
157
172
} ) ;
You can’t perform that action at this time.
0 commit comments