본문 바로가기

Back-End/Node.js

Express - 11. 미들웨어의 실행순서

반응형

목표

미들웨어 실행순서를 next 사용법을 통해 알아보자.

 


 

미들웨어의 유형

 

Express 미들웨어 사용

미들웨어 사용 Express는 자체적인 최소한의 기능을 갖춘 라우팅 및 미들웨어 웹 프레임워크이며, Express 애플리케이션은 기본적으로 일련의 미들웨어 함수 호출입니다. 미들웨어 함수는 요청 오��

expressjs.com

미들웨어에는 여러 종류가 있다.

이전에 다뤄본 미들웨어는 application-level middleware이다. 즉, app변수에는 application 객체가 담겨있는데, 그 객체 중에서 use, get, post를 통해 middleware를 등록하고 사용하는 것이다.

Third-party middleware도 또한 body-parser, compression을 통해 살펴보았다.

Application-level middleware

var app = express();

app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

app.use에 함수를 등록하면, 함수는 middleware로서 등록이 된다.

- req, res 객체를 받아 변형할 수 있다.

- next 함수를 호출받아 다음 실행되어야 할 미들웨어를 실행할지 안할지에 대해 이전 미들웨어가 결정한다.

app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

특정 경로에만 미들웨어가 실행되도록 할 수 있다.

app.get('/user/:id', function (req, res, next) {
  res.send('USER');
});

get을 통해서 메소드가 get인 경우, 특정 경로에만 미들웨어가 실행되도록 할 수 있다.

app.use('/user/:id', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

인자로 함수를 연속적으로 주는 것을 통해 여러 미들웨어를 붙일 수 있다.

첫 함수가 실행되고 나서 next를 호출하면 이는 두 번째 함수를 호출한 것과 같다.

app.get('/user/:id', function (req, res, next) {
  console.log('ID:', req.params.id);
  next();
}, function (req, res, next) {
  res.send('User Info');
});

// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
  res.end(req.params.id);
});

두 미들웨어는 라우트가 동일하다. 위는 두 개의 미들웨어가 등록되어 있고, 아래는 하나의 미들웨어가 등록되어 있다.

이런 경우, 순서에 따라 먼저 위의 미들웨어의 함수가 실행되고, next가 호출되면 다음 미들웨어가 호출된다. 여기서 next를 호출하지 않으므로 res.send를 통해 미들웨어가 끝나게 된다.

next() 사용법

app.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next route
  if (req.params.id == 0) next('route');
  // otherwise pass the control to the next middleware function in this stack
  else next(); //
}, function (req, res, next) {
  // render a regular page
  res.render('regular');
});

// handler for the /user/:id path, which renders a special page
app.get('/user/:id', function (req, res, next) {
  res.render('special');
});

조건문을 통해 다음 미들웨어가 실행될지 안될지 처리할 수도 있다. 만일 req.params.id == 0이라면 next('route')가 실행된다. 이는 다음 라우트의 미들웨어를 실행하라는 뜻이므로 아래 미들웨어를 실행하게 된다.

req.params.id != 0이라면, 즉 else라면 next()가 실행된다. 이는 인자가 없는 next()로 다음 함수를 호출한다.

 

따라서 미들웨어를 잘 설계하면 애플리케이션이 실행되는 흐름을 자유자재로 쉽게 제어할 수 있다.

반응형