Skip to content

Commit

Permalink
[fix]proxy after bodyparser;
Browse files Browse the repository at this point in the history
  • Loading branch information
funkyLover committed Jun 4, 2019
1 parent 9770c5a commit 15b562b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
32 changes: 31 additions & 1 deletion lib/server/proxy.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const queryString = require('querystring');
const koaConnect = require('koa2-connect');
const httpProxy = require('http-proxy-middleware');
const { getStatus } = require('./status');
Expand All @@ -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);
};
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down

0 comments on commit 15b562b

Please sign in to comment.