본문 바로가기

Project/TIL

20.03.14 ShareBook TIL

public listen(){
    const PORT: number = Number(process.env.PORT) || 4000
    this.app.listen(PORT , 0 => { //  <= 여기서 에러
      console.log(`Server listen on PORT ${PORT}`)
    })
  }
  

나는 무슨 생각으로 ()을 0으로 작성했을까...

수정을 하고 다시 서버를 켜보았지만 이번엔 morgan에서 modul을 찾을 수없다는 에러가 생겼다.

devDependencies에는 @type morgan으로 설정하였지만 정작 dependencies에는 설치되어 있지 않았다.

morgan을 설치하고 다시 서버를 켰지만 이번에는 http 404에러가 생겼다.

express.Router()로 다시 path, get()등을 다시 설정하여 서버 작동을 완료하였다.

import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import morgan from 'morgan'; 
import cookieParser from 'cookie-parser';

export default class App {
  // 타입 지정
  public app: express.Application;

  private router: express.Router;

  private path: string;

  constructor() {
    // 사용되는 함수들
    this.app = express();
    this.router = express.Router();
    this.path = '/';

    this.initMiddlewares();
    this.initRouter();
  }

  public listen() {
    // listen()을 실행하기 위해 public으로 지정
    const PORT: number = Number(process.env.PORT) || 4000;
    this.app.listen(PORT, () => {
      console.log(`Server listen on PORT ${PORT}`);
    });
  }

  private initMiddlewares() {
    // 미들웨어 사용
    this.app.use(cors());
    this.app.use(morgan('dev'));
    this.app.use(bodyParser.json());
    this.app.use(cookieParser());
  }

  private initRouter() {
    this.app.use(this.router);
    this.router.get(`${this.path}`, this.getMain);
  }
  
  private getMain = (req: Request, res: Response, next: NextFunction) => {
    res.status(200).send('Server Success!!!!');
  };
}

const app = new App();

app.listen();

 

서버를 처음 켰을때는 200을 보내다 새로고침을 하니 304를 보내서 그 차이점에 대해 찾아보았다.

http 304는 에러가 아니다. not modified로 변경사항이 없음을 나타낸다
클라이언트에서 서버에게 어떤 파일을 요청할때 자신의 HDD 공간에 있는 파일의 정보(마지막으로 변경된 시간이나 파일 크기 등 정보)를 포함해서 서버에게 요청한다(요청헤더에 붙음) 그러면 서버는 클라이언트가 보낸 요청헤더 정보를 보고, 자신의 서버에 있는 파일 정보와 비교한다. 이때 파일 변경시간과 크기등이 서로 같으면 서버는 304로 응답한다. 반대로 파일 변경시간이 서로 틀리거나 파일크기등등이 서로 맞질않으면 이때는 200 응답코드를 받았으므로 기존의 파일이 있다면 삭제하고 새로운 파일로 대체하거나 캐시하게 된다.

'Project > TIL' 카테고리의 다른 글

20.03.16 ShareBook TIL  (0) 2020.03.17
20.03.15 ShareBook TIL  (0) 2020.03.16
20.03.13 ShareBook TIL  (0) 2020.03.13
20.03.12 ShareBook TIL  (0) 2020.03.13
20.03.11 ShareBook TIL  (0) 2020.03.11