@@ -34,28 +34,25 @@ var http = require('http'),
34
34
proxy = httpProxy . createProxyServer ( { } ) ;
35
35
36
36
37
- //restreame
38
- var restreamer = function ( ) {
39
- return function ( req , res , next ) { //restreame
40
- req . removeAllListeners ( 'data' )
41
- req . removeAllListeners ( 'end' )
42
- next ( )
43
- process . nextTick ( function ( ) {
44
- if ( req . body ) {
45
- req . emit ( 'data' , JSON . stringify ( req . body ) )
46
- }
47
- req . emit ( 'end' )
48
- } )
37
+ //restream parsed body before proxying
38
+ proxy . on ( 'proxyReq' , function ( proxyReq , req , res , options ) {
39
+ if ( req . body ) {
40
+ let bodyData = JSON . stringify ( req . body ) ;
41
+ // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
42
+ proxyReq . setHeader ( 'Content-Type' , 'application/json' ) ;
43
+ proxyReq . setHeader ( 'Content-Length' , Buffer . byteLength ( bodyData ) ) ;
44
+ // stream the content
45
+ proxyReq . write ( bodyData ) ;
49
46
}
50
- }
47
+ } ) ;
51
48
52
49
53
50
//
54
51
// Basic Http Proxy Server
55
52
//
56
53
var app = connect ( )
57
- . use ( bodyParser . json ( ) ) //json
58
- . use ( restreamer ( ) ) //restreame
54
+ . use ( bodyParser . json ( ) ) //json parser
55
+ . use ( bodyParser . urlencoded ( ) ) //urlencoded parser
59
56
. use ( function ( req , res ) {
60
57
// modify body here,
61
58
// eg: req.body = {a: 1}.
@@ -84,9 +81,17 @@ http.createServer(app1).listen(9013, function(){
84
81
//request to 8013 to proxy
85
82
request . post ( { //
86
83
url : 'http://127.0.0.1:8013' ,
87
- json : { content : 123 , type : "greeting" }
84
+ json : { content : 123 , type : "greeting from json request" }
85
+ } , function ( err , res , data ) {
86
+ console . log ( 'return for json request:' , err , data )
87
+ } )
88
+
89
+ // application/x-www-form-urlencoded request
90
+ request . post ( { //
91
+ url : 'http://127.0.0.1:8013' ,
92
+ form : { content : 123 , type : "greeting from urlencoded request" }
88
93
} , function ( err , res , data ) {
89
- console . log ( 'return:' , err , data )
94
+ console . log ( 'return for urlencoded request :' , err , data )
90
95
} )
91
96
} ) ;
92
97
0 commit comments