1
1
import express from 'express' ;
2
- import { createProxyServer } from 'http-proxy' ;
2
+ import { ClientRequest } from 'http' ;
3
+ import { createProxyServer , ProxyReqCallback , ProxyResCallback } from 'http-proxy' ;
4
+ import * as querystring from 'querystring' ;
3
5
4
- const proxy = createProxyServer ( { changeOrigin : true } ) ;
6
+ import { ProxyParams } from './stubServer' ;
5
7
6
- // Exported for testing purposes only, see [Jest mock inner function](https://stackoverflow.com/q/51269431)
8
+ // [Body Parsing with express](https://github.com/chimurai/http-proxy-middleware/issues/320)
9
+ const handleBodyParsing : ProxyReqCallback = ( proxyReq , req ) => {
10
+ // @ts -ignore
11
+ const { body } = req ;
7
12
8
- export const send = (
13
+ const contentType = proxyReq . getHeader ( 'Content-Type' ) ;
14
+ const writeBody = ( _body : string ) => {
15
+ proxyReq . setHeader ( 'Content-Length' , Buffer . byteLength ( _body ) ) ;
16
+ proxyReq . write ( _body ) ;
17
+ } ;
18
+
19
+ if (
20
+ contentType === 'application/json' ||
21
+ ( Array . isArray ( contentType ) && contentType . includes ( 'application/json' ) )
22
+ ) {
23
+ writeBody ( JSON . stringify ( body ) ) ;
24
+ }
25
+
26
+ if (
27
+ contentType === 'application/x-www-form-urlencoded' ||
28
+ ( Array . isArray ( contentType ) && contentType . includes ( 'application/x-www-form-urlencoded' ) )
29
+ ) {
30
+ writeBody ( querystring . stringify ( body ) ) ;
31
+ }
32
+ } ;
33
+
34
+ const changeOrigin = ( proxyReq : ClientRequest , origin : string | undefined ) => {
35
+ if ( origin ) {
36
+ proxyReq . setHeader ( 'Origin' , origin ) ;
37
+ }
38
+ } ;
39
+
40
+ const removeSecurityFromCookie : ProxyResCallback = proxyRes => {
41
+ /* eslint-disable no-param-reassign */
42
+ proxyRes . headers [ 'set-cookie' ] = proxyRes . headers [ 'set-cookie' ] ?. map ( ( cookie : string ) =>
43
+ cookie . replace ( 'Path=/; Secure' , 'Path=/' )
44
+ ) ;
45
+ /* eslint-enable no-param-reassign */
46
+ } ;
47
+
48
+ const send = (
9
49
target : string ,
50
+ params : ProxyParams ,
10
51
req : express . Request ,
11
52
res : express . Response ,
12
53
next : express . NextFunction
@@ -21,5 +62,20 @@ export const send = (
21
62
//
22
63
// [Proxy with express.js](https://stackoverflow.com/q/10435407)
23
64
65
+ const { host = false , origin } = params ;
66
+
67
+ const proxy = createProxyServer ( {
68
+ target,
69
+ changeOrigin : true ,
70
+ cookieDomainRewrite : host
71
+ } ) ;
72
+
73
+ proxy . on ( 'proxyReq' , ( proxyReq , ...args ) => {
74
+ changeOrigin ( proxyReq , origin ) ;
75
+ handleBodyParsing ( proxyReq , ...args ) ;
76
+ } ) ;
77
+ proxy . on ( 'proxyRes' , removeSecurityFromCookie ) ;
24
78
proxy . web ( req , res , { target } , next ) ;
25
79
} ;
80
+
81
+ export { send } ;
0 commit comments