L
L
legacy_js2022-01-11 11:51:38
typescript
legacy_js, 2022-01-11 11:51:38

Method does not work in http-proxy-middleware, how to fix it?

From one service I send a request to an address, for example , gateway:3000/users , I proxy using the http-proxy-middleware library on webamqplib:5557 .
Works if I use the function

users.module.ts
// reverse-proxy-middlewareBuilder.ts

import { Request, Response, NextFunction } from 'express';
import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';
import { MiddlewareBuilder } from '@nestjs/core';

export function ReverseProxyMiddleware(req: Request, res: Response, next: NextFunction) {
  const proxy = createProxyMiddleware(req.path, {
    target: 'http://webamqplib:5557/',
    changeOrigin: true,
  })
  proxy(req, res, next)
}

everything works fine, in the console of this service [HPM] Proxy created: /users -> webamqplib:5557
users.module.ts module
// users.module.ts

import { MiddlewareConsumer, Module, NestModule, Param } from '@nestjs/common';
import { ReverseProxyMiddleware } from 'src/reverse-proxy.middleware';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
  controllers: [UsersController],
  providers: []
})
export class UsersModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
      consumer
      .apply(ReverseProxyMiddleware)
      .forRoutes(UsersController)
  }
}


I can’t understand why it doesn’t work through a class
import { Request, Response, NextFunction } from 'express';
import { Injectable, NestMiddleware } from '@nestjs/common';
import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';
import configs from './config/config.json';

@Injectable()
export class ReverseProxyMiddleware implements NestMiddleware {
  private proxy(path: Filter | Options, option?: Options): RequestHandler {
    return createProxyMiddleware(path, option)
  }

  use(req: Request, res: Response, next: () => void) {
    this.proxy(
        req.path, 
        {
          target: configs.users.target,
          changeOrigin: true
        }
      )
    next()
  }
}

When requesting gateway:3000/users in the console, [HPM] Proxy created: /users -> webamqplib:5557 is still displayed , as with the function, but the redirect does not occur to the address as in the first example

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question