Development Notes/JS Patterns
Middleware Pattern
Nomad Kim
2024. 12. 8. 09:44
실제로 요청과 응답 사이에 위치하는 미들웨어 기능 체인으로,
하나 이상의 미들웨어 함수를 통해 요청 객체부터 응답까지 추적하고 수정할 수 있습니다.
const app = require("express")();
const html = require("./data");
app.use(
"/",
(req, res, next) => {
req.headers["test-header"] = 1234;
next();
},
(req, res, next) => {
console.log(`Request has test header: ${!!req.headers["test-header"]}`);
next();
}
);
app.get("/", (req, res) => {
res.set("Content-Type", "text/html");
res.send(Buffer.from(html));
});
app.listen(8080, function() {
console.log("Server is running on 8080");
});
미들웨어 패턴을 사용하면
모든 통신이 하나의 중앙 지점을 통해 이루어지므로
객체 간의 many to many 관계를 쉽게 단순화할 수 있습니다.