diff --git a/lib/server/proxy.js b/lib/server/proxy.js index fe8f69e..ae1cd67 100644 --- a/lib/server/proxy.js +++ b/lib/server/proxy.js @@ -1,3 +1,4 @@ +const queryString = require('querystring'); const koaConnect = require('koa2-connect'); const httpProxy = require('http-proxy-middleware'); const { getStatus } = require('./status'); @@ -9,7 +10,36 @@ const { getStatus } = require('./status'); */ const proxyMiddleware = async (ctx, next) => { const host = getProxyHost(ctx); - const proxy = httpProxy({ target: host, logLevel: 'debug' }); + const proxy = httpProxy({ + target: host, + logLevel: 'debug', + onProxyReq: (proxyReq, req, res) => { + // @NOTE: + // https://github.com/nodejitsu/node-http-proxy/issues/1279 + // https://github.com/chimurai/http-proxy-middleware/issues/299 + // https://github.com/nodejitsu/node-http-proxy/blob/master/examples/middleware/bodyDecoder-middleware.js + req.body = ctx.request.body; + 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)); + proxyReq.write(bodyData); + } + } + }); await koaConnect(proxy)(ctx, next); }; diff --git a/package.json b/package.json index d505b1f..5b96f5b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mock-server-local", - "version": "2.2.0", + "version": "2.2.1", "description": "Mock your apis with a node server", "main": "index.js", "bin": {