1. Application-level 미들웨어

unow30·2020년 10월 18일
0

experss

목록 보기
2/8

1. Application-level 미들웨어

app.use()나 app.METHOD() 함수를 사용하여 app 객체의 인스턴스에 Application-level 미들웨어를 바인딩 할 수 있다.
(app.use([path,] callback[, callback...])는 지정된 경로에 지정된 미들웨어 함수를 마운트한다.)
여기서 METHOD는 미들웨어 함수가 처리하는 요청의 HTTP 메소드(get, post 등)을 소문자로 표시한다.

다음 예는 마운트 경로가 없는 미들웨어 기능을 보여준다. 앱이 요청받을때마다 실행된다.

const express = require('express');
const http = require('http');

let app = express();

app.use(function (req, res, next) {
    console.log('Time:', Date.now())
    next()//다음 미들웨어 실행
})

http.createServer(app).listen(3000, () => { console.log('expresst서버가 3000번 포트에서 시작됨') })
})

이 코드를 nodemon을 이용해 실행시키면 터미널에는
expresst서버가 3000번 포트에서 시작됨이라고 뜬다.
웹 브라우저에 localhost:3000번을 입력하면 웹 화면에는 Cannot GET /이라고 뜨고(html이 없고 웹에 뿌리고 있지 않는다.) 터미널에 Time: 1603014578565현재시간이 뜬다.

이 예시는 마운트 경로(/user/:id)를 가진 미들웨어 함수를 보여준다.

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

localhost:3000/user/:id으로 입력하면 화면에는 Cannot GET /user/:id이라고 뜨고 터미널창에는 Request Type: GET이라고 뜬다.

이 예시는 마운트 경로(/user/:id)와 헨들러 기능(미들웨어 시스템)을 보여준다.

다음 경로에 대한 get 요청을 처리한다.

const express = require('express');
const http = require('http');

let app = express();

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

http.createServer(app).listen(3000, () => { console.log('expresst서버가 3000번 포트에서 시작됨') })

이제 localhost:3000/user/:id를 입력하면 브라우저에 user라는 글이 출력된 것을 확인할 수 있다.

다음은 마운트 경로와 함께 마운트 시점에서 일련의 미들웨어 기능을 로드하는 예시이다.

모든 유형의 http 요청에 대한 req 정보를 (/user/:id path)경로에서 출력하는 미들웨어 하위 스택을 보여준다.

const express = require('express');
const http = require('http');

let app = express();

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

http.createServer(app).listen(3000, () => { console.log('expresst서버가 3000번 포트에서 시작됨') })

app.use(경로, 미들웨어1, 미들웨어2)와 같다. next()가 있어서 다음 미들웨어를 실행시킬 수 있었다. 터미널창에는 다음과 같이 뜬다.
RequestURL: /user/:id
Request Type: GET

Route handlers를 이용해 여러 route를 정의할 수 있다.

이 예시는/ user / : id 경로에 대한 GET 요청의 두 route를 정의한다. 두 번째 route에 문제는 없지만, 첫 번째 route에서 요청- 응답주기를 끝내기 때문에 호출되지 않는다.

// /user/:id 경로가 처음 실행된다.
app.get('/user/:id', function(req, res, next){
  console.log('ID:', req.params.id)
  next()
}, function(req, res, next){
  res.send('User Info')
 //**next()가 없어서 아래 app.get이 실행되지 않는 것인가?
})

// 사용자 ID를 인쇄하는 / user / : id 경로에 대한 핸들러
// 그러나 위에 app.get에서 다음 경로로 요청-응답이 끝났기 때문에
// 이 app은 호출되지 않는다.
app.get('/user/:id', function(req, res, next){
  res.end(req.params.id)
})
//app.get(path, callback)함수로 http get 요청을 지정된 경로로 라우팅한다.

첫 번째 app의 미들웨어로 콘솔에는ID: :id가 뜬다. 두 번째 미들웨어로 웹 화면에 User Info라는 글이 뜬다. 하지만 두 번째 app에서res.end(req.params.id)는 실행되지 않는다.
/user/:id경로로 요청-응답을 끝냈기 때문에 두 번째 app이 실행되지 않는다.

router 미들웨어 스택에서 나머지 미들웨어 기능을 건너뛰려면 next('route')로 제어를 다음 route로 넘긴다.

참고 : next ( 'route')는 app.METHOD () 또는 router.METHOD () 함수를 사용하여 로드 된 미들웨어 함수에서만 작동합니다.

다음 예시는 /user/:id 경로에 대한 get 요청을 처리하는 미들웨어 하위 스택을 보여준다.

const express = require('express');
const http = require('http');

let app = express();
//ready와 set을 출력하는 route
app.get('/user/:id', function (req, res, next) {
    console.log('ready')
    //다음 route로 건너뛰어 아래 미들웨어는 실행되지 않는다.
    next('route');
}, function (req, res, next) {
    //response를 보낸다.
    console.log('set')
})

// 'go'를 출력하는 / user / : id 경로에 대한 핸들러
app.get('/user/:id', function (req, res, next) {
    console.log('go')
})

http.createServer(app).listen(3000, () => { console.log('expresst서버가 3000번 포트에서 시작됨') })

첫 번째 app의 미들웨어에서 ready를 출력한다.
next('route')때문에 아래 미들웨어가 실행 안되고 다음 route인 app.get~이 실행된다.
터미널 출력 결과는 ready go가 된다.

재사용을 위해 미들웨어를 배열로 선언 할 수도 있다. 이 예제는 / ​​user / : id 경로에 대한 GET 요청을 처리하는 미들웨어 하위 스택이있는 어레이를 보여줍니다.

const express = require('express');
const http = require('http');

let app = express();
//ready와 set을 출력하는 route
function logOriginalUrl(req, res, next) {
    console.log('Request URL:', req.originalUrl)
    next()
}

function logMethod(req, res, next) {
    console.log('Request Type:', req.method)
    next()
}

var logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, function (req, res, next) {
    res.send('User Info')
})

http.createServer(app).listen(3000, () => { console.log('expresst서버가 3000번 포트에서 시작됨') })

화면에는 'User Info'가 뜬다. 터미널에는 logStuff 배열 순서대로 함수를 실행시킨 결과인 Request URL: /user/:id Request Type: GET이 출력된다.

1개의 댓글

comment-user-thumbnail
2023년 4월 6일

혹시 application-level 이라는 단어의 개념이 어떤 것인지 간단히라도 알 수 있을까요?

답글 달기