Skip to content

Commit

Permalink
fix: proxy request stuck at loading
Browse files Browse the repository at this point in the history
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: chimurai/http-proxy-middleware#40 (comment)
  • Loading branch information
deshmukhmayur committed May 24, 2023
1 parent 574872b commit 3cb4be2
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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) => {
Expand All @@ -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',
Expand Down

0 comments on commit 3cb4be2

Please sign in to comment.