반응형

아래는 이 글의 동영상 강의입니다.

https://youtu.be/ceNqxXQMuKw

 

* 본 문서는 아래 사이트를 참고하여 작성하였습니다.
https://expressjs.com/ko/guide/using-middleware.html

 

Express 미들웨어 사용

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

expressjs.com

 

Express는 client의 요청을 받아 처리할때 미들웨어라는 개념을 사용합니다.

Express 애플리케이션은 기본적으로 일련의 미들웨어 함수 호출입니다.

 

Express에는 다음과 같은 유형의 미들웨어가 있습니다.

  • 애플리케이션 레벨 미들웨어
  • 라우터 레벨 미들웨어
  • 오류 처리 미들웨어
  • 기본 제공 미들웨어
  • 써드파티 미들웨어

 

애플리케이션 레벨 미들웨어

  • 애플리케이션 미들웨어는 다음과 같이 사용할 수 있습니다.
  • app.use(미들웨어);
  • app.use(미들웨어1, 미들웨어2...);
  • app.use에서 선언된 function이 미들웨어 입니다.
const express = require('express');
const app = express();
app.listen(3000);

app.use(function(req, res){
  res.send('Express Server!!!');
});
  • 한개의 요청을 여러개의 미들웨어가 처리할 수 있습니다.
    • 요청 경로(path)가 포함되지 않은 요청은 항상 실행됩니다.
    • function에서 next 인자를 처리하면 하위 스택을 처리하게 됩니다.
app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});
  • client의 요청 경로(path)가 포함된 경우는 다음과 같이 처리합니다.
    • app.use(path, 미들웨어함수);
app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});
  • 다음은 라우트를 사용하는 방법입니다.
    라우트는 client의 요청을 http method별로 처리할 수 있습니다.
    • app.메소드(path, 미들웨어);
app.get('/user/:id', function (req, res, next) {
  res.send('USER');
});
  • next를 사용해서 미들웨어를 여러개 실행할 수도 있습니다.
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();
});
  • 라우트 핸들러는 하나의 경로에 여러개의 라우트를 정의할 수 있습니다. 하지만 동일한 메소드를 2개 이상 만들고 앞에서 response를 처리하면 다음 메소드는 실행되지 않습니다.
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);
});

 

라우터레벨 미들웨어

  • express.Router()를 사용하면 라우터 레벨의 미들웨어를 사용할 수 있습니다.
var app = express();
var router = express.Router();
  • 위 선언으로 라우터레벨 미들웨어를 다음과 같이 사용할 수 있습니다.
    라우터에서도 use와 method를 사용합니다.
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.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();
});

// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next router
  if (req.params.id == 0) next('route');
  // otherwise pass 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
router.get('/user/:id', function (req, res, next) {
  console.log(req.params.id);
  res.render('special');
});

// mount the router on the app
app.use('/', router);

 

오류 처리 미들웨어

  • 오류 처리 미들웨어는 function의 parameter 첫번째 인자로 error를 받아 처리합니다.
app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

 

기본 제공 미들웨어

  • express에서 기본적으로 제공하는 미들웨어가 있습니다.
  • 다음은 기본제공 미들웨어 중 정적 모듈을 처리하는 static 미들웨어의 예제입니다.
app.use(express.static(__dirname+'/public'))
  • static으로 html 처리
    • http://localhost:3000/index.html 로 요청이 올경우 /public/index.html을 찾아 응답하게 됩니다.
  • static으로 이미지 처리
    • http://localhost:3000/logo.png 로 요청이 올경우 /public/logo.png를 찾아 응답하게 됩니다.
  • index.html 처리하기
    • http://localhost:3000 을 응답하는 코드는 다음과 같습니다.
app.get('/', function(req, res) {
  res.sendFile(__dirname+'/public/index.html')
});

 

써드 파티 미들웨어

  • express에서는 다양한 써드파티 미들웨어를 사용할 수 있습니다.
  • 필요한 기능에 따라 npm install을 사용하여 모듈을 설치하여 사용합니다.
  • 아래는 쿠키 구문 분석 미들웨어인 cookie-parser의 사용 방법 입니다.
  • 우선 cookie-parser 설치합니다.
npm install cookie-parser
  • 사용법은 다음과 같습니다.
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');

// load the cookie-parsing middleware
app.use(cookieParser());
  • 써드파티 미들웨어는 다음 링크에서 확인할 수 있습니다.

https://expressjs.com/ko/resources/middleware.html

 

Express 미들웨어

Express 미들웨어 목록에 적힌 Express 미들웨어 모듈들은 Expressjs 팀이 유지보수합니다. 미들웨어 모듈 설명 내장 함수 (Express 3) body-parser HTTP 요청 body를 파싱합니다. body, co-body, 그리고 raw-body도 참

expressjs.com

 

이상으로 express의 미들웨어에 대해 알아보았습니다.

반응형

+ Recent posts