#3.5 Middlewares part One

jini.choi·2022년 6월 16일
0

유튜브 클론코딩

목록 보기
10/27

Middlewares

  • 중간에 있는 소프트웨어

1. Middlewares는 request와 response 사이에 있다.
브라우저가 request한 다음, 서버가 응답하기 전 Middlewares가 있는 것

2. Middlewares는 handler(controller)고, 모든 handler(controller)는 Middlewares다.
(handler는 사실 controller 였음 앞으로 controller라고 말할거임)

3. controller에는 req, res 말고도 next argument가 더 있다.
next argument는 다음 함수를 호출해준다.

4. 모든 controller는 middleware가 될 수 있다.
하지만 아래 코드에 있는 handleHome은 middleware가 아닌 finalware.
마지막으로 호출되는 함수고 뭐가 됐든 return을 하면 연결이 종료되기 때문

5. middleware는 request에 응답하지 않음. request를 지속 시켜 주는 것

6. middleware는 finalware에 도달하기 전에 무언가를 확인 할 있다.

ex

const gossipMiddleware = (req, res, next) => {
  console.log(`Someone is going to: ${req.url}`);
  next();
};

결과


Code

❓ 아래 코드처럼 end()대신 next()호출하게 되면 브라우저에서 Cannot GET / 이 나온다.
next함수를 호출하면 express가 handleHome의 다음의 함수를 호출 할텐데, 현재 다음 함수가 작성되어 있지 않기 때문이다.

import express from "express"; 

const PORT = 4000;

const app = express();

//application설정
const handlehome = (req, res, next) => {
  next();
};
app.get("/", handlehome); 

const handleListening = () =>
  console.log(`✅ Server listening on port http://localhost:${PORT} 🚀`);
app.listen(PORT, handleListening);

next()를 사용할 수 있게 middleware를 만들어 보자

import express from "express"; 

const PORT = 4000;

const app = express();

//application설정
const gossipMiddleware = (req, res, next) => {
  console.log("middle");
  next();
};
const handlehome = (req, res) => {
  return res.end();
};
app.get("/", gossipMiddleware, handlehome); 

const handleListening = () =>
  console.log(`✅ Server listening on port http://localhost:${PORT} 🚀`);
app.listen(PORT, handleListening);

루틴
1. 브라우저는 홈페이지를 get하려할거고(app.get)

2. 그럼 express가 gossipMiddleware를 호출

3. gossipMiddlewareconsole.log()를 실행하고 next()함수 호출

4. express가 next()를 보고, 다음 함수인 handlehome을 호출

5. handlehomeres.end()호출 후 응답종료

profile
개발짜🏃‍♀️

0개의 댓글