From 3cb4be2f426a9e50f0fd5dba1efa709a0b3d8848 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Wed, 24 May 2023 16:40:38 +0530 Subject: [PATCH] fix: proxy request stuck at loading Moved the body-parser middleware below the http-proxy-middleware A known issue causes unexpected behaviour if the `bodyparser` is loaded before `http-proxy-middleware`. Ref: https://github.com/chimurai/http-proxy-middleware/issues/40#issuecomment-163398924 --- src/server.ts | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/server.ts b/src/server.ts index 2321ad1..2dc38df 100644 --- a/src/server.ts +++ b/src/server.ts @@ -4,7 +4,7 @@ import bodyParser from 'body-parser'; import cookieParser from 'cookie-parser'; import apiKeyRouter from './resolvers/apikeys'; import { ENABLE_API_KEY_AUTH, ROUTE_CONFIG_PATH } from './setup/env'; -import { pinoMiddleware } from './setup/logger'; +import logger, { pinoMiddleware } from './setup/logger'; import { auth } from './middlewares/auth'; import getProxyResolver from './resolvers/proxy'; import { readFileSync } from 'fs'; @@ -14,8 +14,6 @@ import { parse } from 'yaml'; const server = express(); server.use(cors()); -server.use(bodyParser.json()); -server.use(cookieParser()); server.use(pinoMiddleware); server.get('/__ping', (req: Request, res: Response, next: NextFunction) => { @@ -24,20 +22,28 @@ server.get('/__ping', (req: Request, res: Response, next: NextFunction) => { }); }); -if (ENABLE_API_KEY_AUTH) { - /* Setting up routes for API Key management */ - server.use('/_api/apikeys', apiKeyRouter); -} - /* Creating proxy handlers for all the routes defined in config.routes */ +logger.info('Loading route config from ' + ROUTE_CONFIG_PATH); const config: YamlConfig = parse( readFileSync(resolve(ROUTE_CONFIG_PATH)).toString() ); Object.entries(config.routes).forEach((route) => { const [path, options] = route; + logger.info('Registered path: ' + path + ' -> ' + options.target); server.use(path, [auth], getProxyResolver(options)); }); +/** + * Loading the body parser middleware after the http-proxy-middleware due to a known bug + * Ref: https://github.com/chimurai/http-proxy-middleware/issues/40#issuecomment-163398924 + */ +server.use(bodyParser.json()); + +if (ENABLE_API_KEY_AUTH) { + /* Setting up routes for API Key management */ + server.use('/_api/apikeys', apiKeyRouter); +} + server.use('*', (_: Request, res: Response) => { return res.status(404).json({ error: 'Requested resource not found',