dev/nestjs

미들웨어

wlrn566 2023. 2. 7. 17:36

미들웨어는 클라이언트의 요청에 핸들러가 처리하기 전에 코드를 실행할 수 있다.

 

 

미들웨어 클래스를 하나 생성 해준다.

 

import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class MiddlewareTest implements NestMiddleware{
  use(req: any, res: any, next: (error?: any) => void) {
    console.log("middleware");
    next();
  }
}

 

next() 를 넣어 다음 코드를 실행하게 해준다. next()를 하지 않으면 클라이언트는 응답이 없는 상태가 지속된다.

 

 

미들웨어를 사용할 모듈에 configure()를 추가해주고 
.apply() 에 사용할 미들웨어를 넣어주고

.forRoutes() 에 미들웨어를 사용할 경로 또는 컨트롤러를 넣어준다.

 

export class AppModule implements NestModule{
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(MiddlewareTest).forRoutes(AppController)
    // .forRoutes('middle') .forRoutes('m*ddle')
  }
}

 

경로에는 와일드카드 사용도 가능하다.

.exclude() 를 이용해 제외할 경로를 추가할 수 있다.

여러개의 미들웨어, 경로를 콤마로 구분해서 넣을 수 있다.

 

 

미들웨어의 로그가 먼저 찍힌다.

 

 

함수형으로도 구현할 수 있다.

 

import { NextFunction } from 'express';

export function MiddlewareTest(req: Request, res: Response, next: NextFunction) {
  console.log("middleware function");
  next();
}

 

 

함수형 미들웨어를 전역으로 사용 할 수 있다.

 

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { MiddlewareTest } from './middelware';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(MiddlewareTest);
  await app.listen(3000);
}
bootstrap();