배꼽파지 않도록 잘 개발해요

[NestJS] NestJS @Res() 데코레이터를 사용할 때 응답 처리를 직접 제어해야함 본문

BackEnd/Express / NestJS

[NestJS] NestJS @Res() 데코레이터를 사용할 때 응답 처리를 직접 제어해야함

꼽파 2024. 9. 13. 10:25

NestJS를 사용하다보면 express에서 Request와 Response 객체를 직접 import 해야할 일이 있다.
예를 들면 Response 객체를 사용하여 클라이언트에 쿠키를 설정하거나 전송해야하는 일, 미들웨어 작성, 거의 없지만 파일 전송 등의 경우가 있다.

컨트롤러에서 만든 API를 Thunder Client로 테스트하던 도중 응답이 pending 상태가 되는 일이 발생하였다.

 

이럴 경우 무조건 내가 코드를 잘못 쓴 것이기 때문에 컨트롤러부터 살펴봐야한다.

auth.controller.ts 파일을 살펴보니 해당 API에서 @Res() 데코레이터를 주입하여 사용하고 있었다.

 

코드를 아래처럼 수정하면 잘 작동한다.

@Res 데코레이터를 삭제하거나, 아니면 @Res 데코레이터를 사용하면서 response를 직접 제어하면 된다.

 

@Res 데코레이터 사용

async getStatus(
  @SessionUser() sessionUser: IUserWithoutPassword,
  @Res() res: Response,
): Promise<void> { // 반환 타입을 void로 변경
  const { userId } = sessionUser;
  try {
    const statusResponse = await this.authService.sendStatus(userId);
    res.status(HttpStatus.OK).json(statusResponse); // 응답을 직접 설정
  } catch (error) {
    res.status(HttpStatus.BAD_REQUEST).json({ message: '잘못된 요청' });  // 응답을 직접 설정
  }
}

try와 catch문에서 각각 response가 리턴되도록 res.status를 작성하였다.

 

@Res 데코레이터 미사용

async getStatus(
    @SessionUser() sessionUser: IUserWithoutPassword,
  ): Promise<{ message: string }> {
    const { userId } = sessionUser;
    return await this.authService.sendStatus(userId);
  }
}

 

@Res() 데코레이터를 사용하면 NestJS는 직접 응답을 제어하도록 하므로, 메소드에서 반환하는 값을 응답으로 보내지 않는다.

대신 res 객체를 사용하여 직접 응답을 설정해야 한다.

 

https://docs.nestjs.com/controllers

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

코드를 수정하면 잘 작동한다.

728x90