Pushyanth Soma
Pushyanth Soma

Reputation: 56

Angular front end not rerouting to NestJS middleware

Module file:

import { CacheModule, Module, NestModule, RequestMethod } from '@nestjs/common';
import { ServerController } from './server.controller';
import { ReverseProxyMiddleware } from './server.reverse-proxy-middleware';

@Module({
  imports: [CacheModule.register({ ttl: 900 })],
  controllers: [ServerController],
})
export class ServerModule implements NestModule {
  configure(consumer: import('@nestjs/common').MiddlewareConsumer) {
    consumer.apply(ReverseProxyMiddleware).forRoutes({
      path: process.env.PROXY_PATH + '*',
      method: RequestMethod.ALL,
    });
  }
}

Controller file:

import { All, Controller, Get, Header, Req, Res } from '@nestjs/common';
import { Response } from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

@Controller()
export class ServerController {
  @Get('healthcheck')
  healthcheck() {
    return 'OK';
  }

  @All('*')
  @Header('Content-Type', 'text/html')
  root(@Req() request: Request, @Res() response: Response): void {
    response.send(
      readFileSync(join(__dirname, process.env.ANGULAR_ENV, process.env.UserLocation, 'index.html'), {
        encoding: 'utf8',
      })
    );
  }
}

MiddleWare file:

import { ForbiddenException, Injectable, InternalServerErrorException, NestMiddleware } from '@nestjs/common';
import { NextFunction } from 'express';
import https from 'https';

@Injectable()
export class ReverseProxyMiddleware implements NestMiddleware {
  async use(req, res, next: NextFunction) {
    try {
      <code for our service>
    } catch (error) {
      console.log('Error occurred while trying to proxy request : ' + error);
      if (error instanceof ForbiddenException) {
        throw error;
      } else {
        throw new InternalServerErrorException('Could not proxy request');
      }
    }
  }
}

Front end is running on port 4200, backend on 8070, proxy service on 8080 and value for process.env.PROXY_PATH is "/proxy".

When we hit a URL with localhost:4200/proxy prefix, the request is not getting redirected to the proxy MiddleWare. Checked online and it looks like the entire configuration is correct. I'm unable to figure out the issue here.

Upvotes: 0

Views: 31

Answers (0)

Related Questions