[NestJS] 3. Express미들웨어 이해하기 + 활용하기

주수호·2022년 5월 14일
0

미들웨어란

양쪽을 연결하여 데이터를 주고 받을 수 있도록 하는 매개체입니다.


import * as express from "express";
import { Cat, CatType } from "./app.model";

const app: express.Express = express();

// const data = [1, 2, 3, 4];

//middleware
app.use((req, res, next) => {
  //next는 다음라우터로 넘어가는 함수
  console.log(req.rawHeaders[1]);
  console.log("this is middleware");
  next();
});

app.get("/", (req: express.Request, res: express.Response) => {
  console.log(req.rawHeaders[1]); // 어디서 보내는지 확인합니다.
  res.send({ Cat });
});

app.get("/cats/blue", (req, res) => {
  console.log(req.rawHeaders[1]); // 어디서 보내는지 확인합니다.
  res.send({ cats: Cat, blue: Cat[0] });
});

app.get("/cats/som", (req, res, next: express.NextFunction) => {
  console.log(req.rawHeaders[1]); // 어디서 보내는지 확인합니다.
  res.send({ som: Cat[1] });
});

app.listen(8000, () => {
  console.log("server is on.........");
});


이렇게 app.use에서 명시한 middleware가 먼저 실행되어지는 것을 볼 수 있습니다.

! 만약에 endpoint를 지정한 코드가 앞에있다면 어떻게 될까요? res에서 응답을 끝내버리기 때문에, middleware코드는 실행을 하지 않게 됩니다. (순서가 중요하지는 않지만, 직관적이라는 부분은 이해해야합니다. 위->아래 입니다.)

해당 router윗단에 위와 같이 등록을 하게 된다면 어떻게 될까요?

...

app.get("/cats/som", (req, res, next) => {
  console.log("this is som middleware");
  next();
});

...

아래와 같이 나타나게 됩니다.

이렇게 차곡차곡 middleware를 쌓아 나가는 것도 하나의 방법이 될 수 있습니다.

router와 middleware

이를 응용해서 아무요청이 들어왔을 때 이를 404로 반환하는 코드를 만듭니다.

...

app.use((req, res, next) => {
  console.log("this is error middleware");
  res.send({ error: "404 not found error" });
});

endpoint코드들이 있는 맨 마지막 단에 해당 코드를 추가함으로써, 해당 endpoint가 없을 때 에러를 반환하는 코드를 만들었습니다.

express는 기본적으로 이러한 디자인패턴방식을 가집니다.

profile
항상 준비하는 엔지니어

0개의 댓글