| 미들웨어
미들웨어란 양쪽을 연결하여 데이터를 주고받을수 있도록 중간에서 매개역할을 하는것인데
express 공식 문서를보자
Express - Node.js web application framework
Fast, unopinionated, minimalist web framework for Node.js $ npm install express --save
expressjs.com
writing middleware 를 들어가보면 이런 설명이있다
get 라우터를 보면 처음 보는 것이 있다
next
미들웨어 함수에 대한 콜백 인수(일반적으로 'next'라 불린다)
코드를 보며 익혀보자
console.log(req)코드로인해서
아래와 같이 터미널창에 request의 수많은 정보들이 출력되고 있다
이 request속 데이터 중에서 rawHeaders 안에
어디서 요청이 왔는지에대한 정보를 따로 추출해서 출력해보고자한다
위를 보니 6번째(인덱스 5)에 Postman이 있으니까
아래와같이 작성해준다
import * as express from "express";
import { Cat, CatType } from "./app.model";
const app: express.Express = express();
const data = [1, 2, 3, 4];
app.get("/", (req, res) => {
console.log(req.rawHeaders[5]);
res.send({ cats: Cat });
});
app.listen(8000, () => {
console.log("server is on...");
});
잘 출력되는 것을 알 수 있다
이런식으로 서버에는 로그가 출력되게 하고싶은데
만약 라우터가 여러개라면
각각의 라우터마다 다 로그를 출력해주는 코드를 입력하는 것은
코드가 중복되어 비효율적이다!
그래서 미드웨어를 사용하는것인데
아래 그림을 보자
각각의 라우터마다 로그코드의 중복으로인해 양도 많아지고 비효율적이다
이때 미들웨어를 쓴다면 로그코드와 같은 세 라우터가 공통으로 갖고있는 코드를 미들웨어에게 넘기고
라우터는 오로지 요청에에 해당하는 비즈니스 로직만 수행하게끔 기능을 분리하는것이 더 효율적이다
코드를 보자
import * as express from "express";
import { Cat, CatType } from "./app.model";
const app: express.Express = express();
app.use((req, res, next) => {
console.log(req.rawHeaders[5]);
next();
});
app.get("/", (req, res) => {
res.send({ cats: Cat });
});
app.get("/cats/blue", (req, res) => {
res.send({ blue: Cat[0] });
});
app.get("/cats/som", (req, res) => {
res.send({ blue: Cat[1] });
});
app.listen(8000, () => {
console.log("server is on...");
});
그리고 cats/blue로 요청을하면
로그도 잘 출력되는것을 볼 수 있다
top to bottom 이라
미들웨어가 제일 위에 있기때문에
미들웨어를 먼저 거친 후 미들웨어 코드를 수행하고
마지막에 있는 next() 함수를 통해
해당하는 라우터를 찾아 실행하게 된다
만약 미들웨어가 제일 아래에 있다면?
import * as express from "express";
import { Cat, CatType } from "./app.model";
const app: express.Express = express();
app.get("/", (req, res) => {
res.send({ cats: Cat });
});
app.get("/cats/blue", (req, res) => {
res.send({ blue: Cat[0] });
});
app.get("/cats/som", (req, res) => {
res.send({ blue: Cat[1] });
});
app.use((req, res, next) => {
console.log(req.rawHeaders[5]);
next();
});
app.listen(8000, () => {
console.log("server is on...");
});
똑같이 postman에
http://localhost:8000/cats/blue
를 요청했지만 미들웨어가 실행되지 않았음을 확인할 수 있다
이유는 미들웨어가 라우터들 보다 아래에 있고
express가 해당하는 라우터를 먼저 찾으면
응답이 끝나기때문에 미들웨어가 실행되지 않는다
만약 해당하는 엔드포인트와 해당하는 http method 에서만 미들웨어가 수행하도록 하려면
use대신 해당 http method를 사용하면 된다
use를 쓰는 이유는 특정 경로나 HTTP 메서드에 상관없이 요청이 처리되기 전에 실행되는 미들웨어를 등록할 때 주로 사용하기위해서다
아래와 같이 라우터와 비슷하지만 next 매개변수를 넣어으면된다
import * as express from "express";
import { Cat, CatType } from "./app.model";
const app: express.Express = express();
app.use((req, res, next) => {
console.log(req.rawHeaders[5]);
console.log("this is logging middleware");
next();
});
app.get("/cats/som", (req, res, next) => {
console.log(req.rawHeaders[5]);
console.log("this is som middleware");
next();
});
app.get("/", (req, res) => {
res.send({ cats: Cat });
});
app.get("/cats/blue", (req, res) => {
res.send({ blue: Cat[0] });
});
app.get("/cats/som", (req, res) => {
res.send({ blue: Cat[1] });
});
app.listen(8000, () => {
console.log("server is on...");
});
콘솔을 보면 아래와 같이 출력된다
그림을 통해 순서를 설명하자면
이게 가장 기본적인 express 의 라우터와 미들웨어 디자인 패턴이다
응용을 하자면
만약 존재하지않는 라우터에게 요청을보내서 404 not found error를 찍어보게하자
그럴땐 제일 아래에 use미들웨어를 두어 console을 찍게 하면 된다
import * as express from "express";
import { Cat, CatType } from "./app.model";
const app: express.Express = express();
app.use((req, res, next) => {
console.log(req.rawHeaders[5]);
console.log("this is logging middleware");
next();
});
app.get("/cats/som", (req, res, next) => {
console.log(req.rawHeaders[5]);
console.log("this is som middleware");
next();
});
app.get("/", (req, res) => {
res.send({ cats: Cat });
});
app.get("/cats/blue", (req, res) => {
res.send({ blue: Cat[0] });
});
app.get("/cats/som", (req, res) => {
res.send({ blue: Cat[1] });
});
app.use((req, res, next) => {
console.log("this is error middleware");
res.send({ error: "404 not found error" });
});
app.listen(8000, () => {
console.log("server is on...");
});
'웹 개발 > 🟩 Node.js' 카테고리의 다른 글
Express | route분리, 모듈화 (0) | 2023.06.18 |
---|---|
Express | Create Read API 개발 (0) | 2023.06.18 |
Express | 데이터 모킹 (0) | 2023.06.13 |
Express | express, ts 개발 환경 셋업, helloworld출력하기 (0) | 2023.06.12 |
Express | Node, VSCode, Prettier 개발환경세팅 (0) | 2023.06.05 |