From a3fe02d651d05d02d0ced377c22ae8345a2435a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=BB=E4=BE=A0?= Date: Thu, 7 Jun 2018 00:39:50 +0800 Subject: [PATCH] [examples] Restream body before proxying, support for Content-Type of application/x-www-form-urlencoded (#1264) --- examples/middleware/bodyDecoder-middleware.js | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/examples/middleware/bodyDecoder-middleware.js b/examples/middleware/bodyDecoder-middleware.js index 38559ef3b..71e16c8ac 100644 --- a/examples/middleware/bodyDecoder-middleware.js +++ b/examples/middleware/bodyDecoder-middleware.js @@ -29,6 +29,7 @@ var http = require('http'), request = require('request'), colors = require('colors'), util = require('util'), + queryString = require('querystring'), bodyParser = require('body-parser'), httpProxy = require('../../lib/http-proxy'), proxy = httpProxy.createProxyServer({}); @@ -36,12 +37,23 @@ var http = require('http'), //restream parsed body before proxying proxy.on('proxyReq', function(proxyReq, req, res, options) { - if(req.body) { - let bodyData = JSON.stringify(req.body); - // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json - proxyReq.setHeader('Content-Type','application/json'); + if (!req.body || !Object.keys(req.body).length) { + return; + } + + var contentType = proxyReq.getHeader('Content-Type'); + var bodyData; + + if (contentType === 'application/json') { + bodyData = JSON.stringify(req.body); + } + + if (contentType === 'application/x-www-form-urlencoded') { + bodyData = queryString.stringify(req.body); + } + + if (bodyData) { proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData)); - // stream the content proxyReq.write(bodyData); } }); @@ -94,5 +106,3 @@ http.createServer(app1).listen(9013, function(){ console.log('return for urlencoded request:' ,err, data) }) }); - -