Develop Dairy/JavaScript, React

Middlewares 익스프레스의 미들웨어의 이해

개발자_옹이양 2019. 1. 19. 11:08

express에서 middleware란 처리가 끝날 때까지 연결되어있는


어떻게 연결이 시작되느냐 


아래코드상에서 설명을 해준다


import express from "express";
const app = express();

const PORT = 4000;

const handleListening = (req, res) => console.log(`Listening on: http://localhost:${PORT}`);


const handleHome = (req, res) => {
console.log(req);
res.send("Hello from home");
}

const handleProfile = (req, res) => res.send("You are on my profile @@");

app.get("/",handleHome);

app.get("/profile", handleProfile);

app.listen(PORT, handleListening);



우리가흔히생각하는 브라우저


브라우저에 서 URL로 접속을 시도하면 

Index파일을 실행 -> application이 route가 존재하는지 살펴봄 코드상에서 app.get("/",handleHome); "/"이부분./부분을 찾은다음 ->  handleHome이라는 함수를 실행 -> hadnleHome은 응답을 전송한다



근데 보통 연결은 그렇게 간단히 되지 않는다.


보통 중간에 뭔가가 있게 되는데 유저와 마지막 응답 사이에.

이걸 middleware라고 한다. express에서의 모든함수는 middleware가 될 수 있다.


바꿔보자

app.get("/",handleHome);  -> app.get("/", betweenHome, handleHome);




beginning과 start 사이에 있으니까 home(/)요청과 handleHome사이에 있는 

구글 크롬으로부터 온 요청을 계속 처리할 지에 대해 권한을 주지 않았기 때문에

handleHome으로 처리될지를 그 요청을 계속 처리할수있는 권한을 줘야하는것이다.


그래서 내가 할 건 next라고 하는 key를 이용할것


express의 모든 route와 그런 connection은 request, response, next를 갖고 있다.



middleware를 호출할 거다 그리고 호출한함수가 나타나는 것

const handleHome = (req, res) => res.send("Hello from home");

const betweenHome = (req, res, next) => {
console.log("Between");
next();
}

app.get("/", betweenHome, handleHome);

/ -> betweenHome -> handleHome


hadnleHome은 res.send를 반환


내가 원하는 만큼 middleware를 가질 수 있는데

 

예를들어 

middleware로 유저의 로그인 여부를 체크할 수 있고

파일을 전송할 때 중간에서 가로챌 수도 있고

로그를 작성하는 middleware도 가질 수 있고 모든접속에 대하여



위에서 쓴 betweenHome 미들웨어는 route에서만 썻다


또다르게 써보면

웹사이트에서 일어나는 모든 것에대해 middleware를 써보려고한다.


와같이 바꿔보았다


접속경로 "/", "/profile" 접속할때마다 Between 이 log되는걸 볼 수 있다.




app.use의 순서가 중요하다

접속이 있을 때 말야 위에서부터 아래로 실행이 되기때문


app.use 다음 rotue가 반환되는것 

app.use(betweenHome);

app.get("/", handleHome);


원하는 만큼의 middleware를 두고 그다음에 route를 처리


예를들면

app.get("/", handleHome);

app.use(betweenHome);

app.get("/profile", handleProfile);

로되어있으면

/로접속했을때는 미들웨어가 실행이안되다가  /profile에 접속하면 미들웨어가 실행이됩니다.