Skip to content

Commit

Permalink
FIX: Proxying was not working for POSTs with bodies
Browse files Browse the repository at this point in the history
 * http-proxy-middleware was not passing the POST body along - it was being dropped
 * There are lots of threads on this, but the most helpful was here:
chimurai/http-proxy-middleware#40 (comment)
 * Followed advice and recipe
(https://github.com/http-party/node-http-proxy/blob/master/examples/middleware/bodyDecoder-middleware.js) to parse body and
then re-stream in request
 * Tested and working with POST and even application/x-www-form-urlencoded
  • Loading branch information
joshuatz committed Dec 3, 2019
1 parent a06b5e3 commit 85215fa
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
46 changes: 41 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,55 @@
// @ts-check

const express = require('express');
const config = require('./config');
const proxy = require('http-proxy-middleware');
const bodyParser = require('body-parser');
const queryString = require('querystring');

// Create proxy instance
const proxyInstance = getProxy();

const app = express();
app.all('*', getProxy());
app.use('/', proxyInstance);

// Optional: Support special POST bodies - requires restreaming (see below)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

function getProxy() {
return proxy({
return proxy(getProxyConfig());
}

/**
* @returns {import('http-proxy-middleware').Config}
*/
function getProxyConfig() {
return {
target: config.destination,
changeOrigin: true,
followRedirects: true,
secure: true
});
secure: true,
onProxyReq: (proxyReq, req, res, options) => {
// Restream parsed body before proxying
// https://github.com/http-party/node-http-proxy/blob/master/examples/middleware/bodyDecoder-middleware.js
if (!req.body || !Object.keys(req.body).length) {
return;
}
const contentType = proxyReq.getHeader('Content-Type');
let 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);
}
}
};
}

module.exports = {
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "gcp-proxy-func",
"version": "1.0.0",
"version": "1.0.1",
"description": "Google Cloud Function that proxies requests to a host specified in config.",
"main": "index.js",
"scripts": {
Expand All @@ -13,7 +13,9 @@
"license": "MIT",
"devDependencies": {},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"http-proxy-middleware": "^0.20.0"
"http-proxy-middleware": "^0.20.0",
"querystring": "^0.2.0"
}
}

0 comments on commit 85215fa

Please sign in to comment.