티스토리 뷰

미들웨어

  • express 내에서 중간 처리함수
  • 미들웨어를 통해서 request를 받고, response를 한다.
  • 미들웨어 함수는 코드 line 순서대로 실행된다.

 

const express = require('express');

const app = express(); //express로부터 객체 생성 

app.use('/' ,(req,res,next)=>{}); //미들웨어 함수 

express.listen(3000); // 서버 생성 

 

  • use는 app의 메서드로서, 새로운 미들웨어 함수가 적용된다. 
  • 콜백 함수가 미들웨어 함수가 되고 next는 또다른 콜백함수로서 다음 미들웨어 함수를 호출하게 해준다. 
  • '/' 인자는 해당 미들웨어 함수가 적용될 route를 가리킨다. 

 

주의점

  • 미들웨어 함수는 next()를 호출하던가, response를 해주어야 한다. 그렇지 않으면 그대로 서버가 응답하지 않는다. 여기서 next()는 다음 응답을 미들웨어 함수로 넘기는 것이고 response는 해당 미들웨어 함수에서 응답한다는 것이다.
  • 미들웨어 함수는 코드 라인의 순서대로 넘겨지기 때문에 route handling에서 주의해야한다. 가령, '/' 를 처리하는 미들웨어 함수를 맨 앞에 놓고 응답을 해버리면, 다른 route를 처리하는 미들웨어 함수들은 호출이 되지 않는다. 모든 url이 / 로 시작하기 때문이다. 

 

 

이를 적용해서 여러개의 미들웨어 함수를 만들어서, 각각의 route에 적용되게 만들어보면 아래와 같다. 

const express = require('express');

const app = express();

app.use('/',(req,res,next)=>{

    console.log('first middleware');
    next(); //next 혹은 response를 해야함. next는 다음 미들웨어로 넘긴다는 뜻 
});

app.use('/add-product',(req,res,next)=>{

    console.log('second middleware');
    res.send('<h1>this is add product page! </h1>');

});

app.use('/',(req,res,next)=>{

    console.log('third middleware');
    res.send('<h1>hello welcome! </h1>');

});


app.listen(3000);

 

 

참조 : https://expressjs.com/en/guide/writing-middleware.html

 

Writing middleware for use in Express apps

Writing middleware for use in Express apps Overview Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a func

expressjs.com

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함