@@ -34,28 +34,25 @@ var http = require('http'),
3434 proxy = httpProxy . createProxyServer ( { } ) ;
3535
3636
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 ) ;
4946 }
50- }
47+ } ) ;
5148
5249
5350//
5451// Basic Http Proxy Server
5552//
5653var app = connect ( )
57- . use ( bodyParser . json ( ) ) //json
58- . use ( restreamer ( ) ) //restreame
54+ . use ( bodyParser . json ( ) ) //json parser
55+ . use ( bodyParser . urlencoded ( ) ) //urlencoded parser
5956 . use ( function ( req , res ) {
6057 // modify body here,
6158 // eg: req.body = {a: 1}.
@@ -84,9 +81,17 @@ http.createServer(app1).listen(9013, function(){
8481 //request to 8013 to proxy
8582 request . post ( { //
8683 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" }
8893 } , function ( err , res , data ) {
89- console . log ( 'return:' , err , data )
94+ console . log ( 'return for urlencoded request :' , err , data )
9095 } )
9196} ) ;
9297
0 commit comments