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 ee24d08
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 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 @@ -30,14 +28,22 @@ if (ENABLE_API_KEY_AUTH) {
}

/* 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());

server.use('*', (_: Request, res: Response) => {
return res.status(404).json({
error: 'Requested resource not found',
Expand Down

0 comments on commit ee24d08

Please sign in to comment.