TIL 44 | Express 미들웨어 만들기

dabin *.◟(ˊᗨˋ)◞.*·2021년 9월 23일
0

Node.js

목록 보기
7/11
post-thumbnail

생활코딩 강의를 보고 작성하였습니다.
https://opentutorials.org/course/3370/21398

미들웨어 만들기

http://expressjs.com/en/guide/writing-middleware.html#mw-fig

var express = require('express')
var app = express()

var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)

myLogger과 같은 방식으로 직접 미들웨어를 만들어 사용할 수 있다. 자주 사용된 로직이 있을 때 미들웨어로 만들어 사용하면 효과적이다. 이전에 작성한 코드에서는 fs.readdir가 반복되었으니, 이를 미들웨어로 만들어보자.

//next에는 다음에 호출되어야 할 미들웨어가 담겨 있다. 
app.use((req, res, next) => {
  fs.readdir('/data', (error, filelist) => {
  	req.list = filelist;
    next(); //미들웨어 실행
  })
})

//post방식에서는 filelist를 읽어야할 필요가 없어 모든 요청에 적용되면 비효율적이다. 
//get메서드 요청에만 적용되게 만들어준다. 
app.get('*', (req, res, next) => {
  fs.readdir('/data', (error, filelist) => {
  	req.list = filelist;
    next(); 
  });
});

app.get('/', (req, res) => {
    const title = 'Welcome';
    const description = 'Hello, Node.js';
    const list = template.list(req.list);
    const html = template.HTML(title, list,
      `<h2>${title}</h2>${description}`,
      `<a href="/create">create</a>`
    );
    res.send(html)
})

이렇게 만들고 보니, app 메서드의 두번째 인자로 오는 콜백함수는 미들웨어라는 것을 알 수 있다. Express에서는 사실 모든 것이 미들웨어라고 보면 된다. 애플리케이션이 구동될 때 순서대로 등록되어 있는 조그만한 프로그램들이 실행되는데, 각각의 프로그램들이 서로를 연결해주는 작은 소프트웨어라는 점에서 미들웨어!라고 생각하자.

미들웨어의 실행 순서

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

  • Application-level middleware : app.get/use/post 등의 방식으로 등록된 미들웨어
  • Router-level middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

http://expressjs.com/en/guide/using-middleware.html#middleware.application

  1. 경로와 메서드를 정의할 수 있다.
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')
})
  1. 미들웨어를 여러개 붙일 수 있다.
app.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next() //next()를 호출하면 다음 함수가 실행된다. 
}, function (req, res, next) {
  console.log('Request Type:', req.method)
  next() //순서대로 실행!! 
})
  1. how to define multiple routes for a path
//두 개의 미들웨어
app.get('/user/:id', function (req, res, next) {
  //1
  console.log('ID:', req.params.id)
  next() //2 다음함수호출
}, function (req, res, next) {
  //3
  res.send('User Info')
  //4 next() 호출하지 않았기 때문에 요청이 끝남
})

// handler for the /user/:id path, which prints the user ID
//하나의 미들웨어
app.get('/user/:id', function (req, res, next) {
  res.send(req.params.id)
})
  1. 조건문에 따라 next() 호출
app.get('/user/:id', function (req, res, next) {
  if (req.params.id === '0') next('route') 
  //1 조건문이 true라면 다음 route의 미들웨어를 실행시켜줘!
  else next() //3 조건문 false라면 
}, function (req, res, next) { //4 실행됨
  res.send('regular')
})

app.get('/user/:id', function (req, res, next) {//2 1번에 따라 실행됨
  res.send('special')
})
profile
모르는것투성이

0개의 댓글