유튜브 클로닝 #2-2 Server: middleware
3151 단어 강의youtubemiddlewaremiddleware
Middleware
예제
// though it starts with middleware "one" it will eventually end up with a controller "three" because next() was called.
// You can put codes inside a body of middlewares "one" and "two" to check something before they get to the controller "three"
const one = (req,res,next) => {
next();
}
const two = (req,res,next) => {
next();
}
const three = (req,res) => {
console.log("Now three is handling")
}
// app.get will handle users who visit "/" URL with "one" handler
app.get("/login", one, two, three)
이중 마지막으로 브라우저에게 응답하는 finalware(three) 를 제외하고 모두(one, two)는 middleware이다. /login 페이지로 이동시 one, two, three 가 순차적으로 발동된다.
설명
- Middlewares are software between request and response.🌟
- All middlewares are handlers. All controllers are middlewares.
- They have three arguments including next argument. (req, res, next) 🌟
- Next argument calls [next()] the next handler function if it exists.
- app.use() 를 통해 app 내에 어떤 url 에도 발동되는 middleware 를 만들 수 도 있다. 아래와 같이:🌟
// though it starts with middleware "one" it will eventually end up with a controller "three" because next() was called.
// You can put codes inside a body of middlewares "one" and "two" to check something before they get to the controller "three"
const one = (req,res,next) => {
next();
}
const two = (req,res,next) => {
next();
}
const three = (req,res) => {
console.log("Now three is handling")
}
// app.get will handle users who visit "/" URL with "one" handler
app.use(one)
app.use(two)
app.get("/login", three)
one, two 는 app 내의 어떤 페이지로 이동해도 발동된다. three 는 /login 페이지로 갔을 때만 발동된다.
기타: Morgan 패키지
morgan
:자동으로 middleware 를 생성해주는 패키지
morgan 설치
npm i morgan
https://www.npmjs.com/package/morgan
morgan 사용
import morgan from "morgan" // morgan 패키지 불러오기
const logger = morgan("dev") // morgan 으로 middleware 생성 완료
https://www.npmjs.com/package/morgan#examples
? 의문점
핸들러 vs. 컨트롤러 vs. 미들웨어 한번에 정리:
- handler: 특정 url 로 이동시 발동되는 모든 함수들.
- controller: handler 중 res 를 컨트롤 하는 함수. 즉, 브라우저에 직접 응답하는 함수. 조건문을 통해 middleware 도 controller 가 될 수 있다.
- finalware: handler 들 중 가장 마지막에 발동되는 함수. 반드시 res 를 포함한다.
- middleware: finalware 가 아닌 모든 핸들러들. 조건에 따라 res 를 발동시킬 수도 있다. next() 를 반드시 포함하여 다음 핸들러로 넘어갈 수 있게끔 한다.
🌟 요약
- 미들웨어는 컨트롤러 전에 오는 모든 함수들. next 를 세번째 인자로 포함.
- app.get("url", middleware1, middleware2,....,controller) : 특정 url 에서만 발동하는 미들웨어 만들기
app.use(middleware): 앱 내에 어떤 url 에서도 발동하는 함수 만들기. 이때 app.use() 는 반드시 app.get() 보다 앞서 적혀야한다. - 더 정교한 미들웨어(500줄)를 보다 손쉽게 자동으로 생성하는 패키지: morgan
Author And Source
이 문제에 관하여(유튜브 클로닝 #2-2 Server: middleware), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jlee0505/유튜브-클로닝-2-2-Server-middleware저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)