inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

Slack 클론 코딩[백엔드 with NestJS + TypeORM]

loggerMiddleware로 morgan처럼 로깅하기

.env 파일에 3030 포트로 동일하게 작성했지만 사이트에 연결할 수 없음이 나오는데 어디 부분이 빠진 건가요?

해결된 질문

480

dev kim

작성한 질문수 12

0

안녕하세요. 포트 3000 에서는 사이트도 잘 뜨고 로깅도 잘 되고 있습니다.

다만, 환경변수 파일에 추가한 3030 포트로는 열리지 않고 있습니다. 어디 부분을 확인해봐야 되나요??

SECRET=제로초강의
PORT=3030

 

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

declare const module: any;

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const port = process.env.PORT || 3000;
  await app.listen(3000);
  console.log(`listening on port ${port}`);

  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}

bootstrap();

 

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

// 서비스의 경우, 요청과 응답에 대해서는 모르기 때문에 독립적이다.
// 즉, 로직을 작성하는 공간이라고 생각하면 된다.
@Injectable()
export class AppService {
  constructor(private readonly configService: ConfigService) {}
  getHello(): string {
    // process.env.PORT보단 get으로 가져오는 것이 좋다.
    // return this.configService.get('SECRET');
    return process.env.SECRET;
  }
}

 

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerMiddleware } from './middlewares/logger.middleware';

@Module({
  imports: [ConfigModule.forRoot()],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer): any {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}

 

import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private logger = new Logger('HTTP');

  use(request: Request, response: Response, next: NextFunction): void {
    const { ip, method, originalUrl } = request;
    const userAgent = request.get('user-agent') || '';

    response.on('finish', () => {
      const { statusCode } = response;
      const contentLenth = response.get('content-length');

      // 만약 context가 필요가 없을 경우 Logger.log가 console.log 대체이다.
      this.logger.log(
        `${method} ${originalUrl} ${statusCode} ${contentLenth} - ${userAgent} ${ip}`,
      );
    });
    next();
  }
}

 

node.js express nestjs typeorm

답변 1

1

제로초(조현영)

app.listen에 3000으로 고정되어있습니다. 이걸 바꾸세요

0

dev kim

아..! 해결되었습니다. 감사합니다.

강의자료는 어디서 다운받나요?

0

110

3

질문 있습니다.

0

294

3

(강의 5:42 질문) providers를 통한 여러 개의 인스턴스 생성 & exports 통한 싱글톤 생성

0

154

2

코드 편집기 확장 프로그램

0

209

2

(질문)비밀 저장소에 접근하기 위한 인증 정보는 로컬 .env에 저장하는지?

0

143

2

(질문)외부 저장소를 통한 환경변수 불러오기 비동기 질문

0

166

3

로그인을 해도 LoggedInGuard쪽에서 false값이 나옵니다.

0

152

2

로그인방법이 고민됩니다.

0

190

2

yarn seed 명령어 실행 시 데이터 삽입 안됨

0

296

4

yarn run db:create 시에 발생하는 데코레이터 오류

0

242

2

npm run db:create 시에 발생하는 decorating 오류

0

231

2

RxJS 디버깅 질문 있습니다.

0

187

3

CacheManager에 대해 질문 있습니다.

0

173

2

로깅은 어떻게 하는게 효율적일까요?

0

224

1

CORS 질문 있습니다.

0

417

2

쿠키 옵션에 대해서 질문 있습니다.

0

184

2

로그아웃 요청이 403 forbidden 에러가 나는데 왜그런걸까요??

0

447

1

401 unauthorized문제

0

286

1

가드의 장점에 대해서 질문이 있습니다.

0

225

1

로그 관리에 대해 질문 있습니다.

0

252

2

CORS 에러 질문 있습니다.

0

318

2

배포 환경 DB 연결 질문 있습니다.

0

411

2

socket io 미 연결 문제 (nest & flutter)

1

1154

3

no elements in sequence 에러 관해서 질문이 있습니다.

0

454

1