Here is the code for a provider:
@Injectable()
export class GameServerProxyService {
private httpProxy: httpProxy;
constructor(@Inject(GameServerDetailsService) private gameServiceDetailsService: GameServerDetailsService) {
this.httpProxy = httpProxy.createProxyServer({});
this.httpProxy.on("proxyReq", (err,req,res)=>{
console.log("proxyReq");
});
this.httpProxy.on("proxyRes", (err,req,res)=>{
console.log("proxyRes");
});
this.httpProxy.on("error", (err,req,res)=>{
console.error(err);
});
}
proxyRequest(request: Request, response: Response){
console.log("proxyRequest");
this.httpProxy.web(request, response, {
target: "http://localhost:3100/",
changeOrigin: true,
}, (error) => {
console.log(error);
});
}
}
Below is a controller that uses the above provider to proxy calls:
@Controller()
export class SsrApiGatewayController {
constructor(
@Inject(GameServerProxyService) private gameServerProxyService: GameServerProxyService
) { }
@All("game-server/*")
async proxyGameServerRequest(@Req() request: Request, @Res() response: Response) {
console.log("Proxying Request..!")
this.gameServerProxyService.proxyRequest(request, response);
}
}
The issue I am facing is that when I send a request to the route handled by the controller, my request seems to stall. The logs show:
Proxy Request..!
proxyReq
This indicates that the proxied request never reaches the response stage. Upon canceling the stalled request, I receive an error from the server being proxied to (http://localhost:3100/):
[Nest] 6220 - 01/27/2022, 7:41:35 PM ERROR [ExceptionsHandler] request aborted
BadRequestError: request aborted
at IncomingMessage.onAborted (C:\******\node_modules\raw-body\index.js:231:10)
at IncomingMessage.emit (events.js:314:20)
at IncomingMessage.EventEmitter.emit (domain.js:483:12)
at abortIncoming (_http_server.js:533:9)
at socketOnClose (_http_server.js:526:3)
at Socket.emit (events.js:326:22)
at Socket.EventEmitter.emit (domain.js:483:12)
at TCP.<anonymous> (net.js:675:12)
The request is being proxied forward but there is no response coming back.
Interestingly, using http-proxy-middleware
instead of http-proxy
solves the problem. This middleware configuration works smoothly:
async function bootstrap() {
const app = await NestFactory.create(SsrApiGatewayModule);
app.useGlobalPipes(
new ValidationPipe({
transform: true,
whitelist: true,
}),
);
app.use("/game-server/*",
createProxyMiddleware({
target: "http://localhost:3100",
changeOrigin: true,
})
);
var configService = app.get(ConfigService);
var commonConfig = configService.get<CommonConfig>(CommonKey);
await app.listen(commonConfig.port);
}
Despite this workaround, I want to leverage my custom provider because it allows for a more intricate router setup and access to other injected providers within NestJS ecosystem.
The reason behind the request stalling despite various attempts including implementing a NestJS middleware with http-proxy-middleware
wrapped inside remains unclear.