상세 컨텐츠

본문 제목

Express: 라우팅과 미들웨어

자바스크립트

by lazz 2021. 9. 6. 23:43

본문

반응형

 

 

Routing

app.METHOD(PATH, HANDLER)

app.get('/', (req, res) => {
	res.send('Hello world');
});

HTTP GET method를 처리

app.all() // 모든 HTTP methods
app.use() // specify middleware as the callback function

 

routing path의 ? + * ()는 regex의 subset이다.

 

미들웨어

 

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

Application request-response cycle에서 아래 목록에 접근할 수 있는 함수

  • request object (req)
  • response object (res)
  • next

 

next

Express router의 함수

현재 middleware 다음의 middleware를 실행

req res next 다 컨벤션이니 지키도록 하자.

 

middleware 함수는 다음과 같은 일을 할 수 있다

  • 임의의 코드 실행
  • request & response object 변경
  • request-response cycle 종료
  • 스택의 다음 middleware 실행

만일 현재 middleware 함수가 request-response cycle을 끝내지 않으면 next()를 불러서 다음 middleware 함수를 호출해야 한다.

next()를 호출하고 처리하지 않으면 오른쪽 이미지처럼 에러가 발생한다.

 

 

 

Middleware 함수 작성하기

app.use()를 호출해 인자로 middleware 함수를 넣으면 middleware 함수를 사용할 수 있다

Request를 받을 때 마다 LOGGED를 출력한다.

 

middleware의 순서는 중요하다. 만약 myLogger를 get 뒤에 로드하게 되면 get이 request-response cycle을 종료하기 때문에 실행되지 않는다.

위에 언급한 것 처럼 req res 객체를 변경하고 다음 middleware 함수를 호출할 수 있다.

 

 

 

미들웨어 종류

Application-level middleware

app.use() 혹은 app.METHOD() 함수로 미들웨어 함수와 app을 바인드 할 수 있다. METHOD는 GET, PUT, POST같은 http method를 의미한다.

경로를 명시하지 않은 경우 모든 request 마다 함수가 실행된다.

 

/user/:id 경로로 들어온 모든 http request마다 실행된다.

 

위의 get 함수의 next()로 호출하는 미들웨어에서 요청에대한 응답을 보내면서 request-response cycle를 종료하기 때문에 두번째 get 미들웨어는 평생 실행되지 않는다.

 

router 미들웨어 스택의 나머지를 스킵하고 싶다면 next('route) 함수를 불러서 다음 route에게 넘겨줄 수 있다.

위 경우 id값이 0인 경우 special을 응답으로 보내고 나머지 경우에는 regular를 응답으로 보낸다.

 

주의: next('route')는 app.METHOD()와 router.METHOD()로 로드된 미들웨어에서만 사용 가능하다.

 

여러 개의 미들웨어를 등록해 미리 순차적으로 미들웨어를 거칠 수 있다. 위의 예제는 post request가 들어오면 url를 찍고 method를 찍은 뒤 content-type이 application/json이면 'You sent JSON'로 응답하고 아니라면 400에러로 응답한다.

 

미들웨어 함수를 배열에 넣어서 직관적으로 사용할 수 있다.

 

 

 

Router-level middleware

express.router()의 인스턴스에만 사용할 수 있는 미들웨어.

사용법은 application level middleware와 크게 다르지 않다. 다만 router에 미들웨어를 로드하고, 그 라우터를 app에 등록해야 한다.

 

 

 

Error-handling middleware

기존의 req, res, next에 err 까지 더한 총 4개의 argument를 받는 middleware 함수를 정의하면 에러 핸들링을 하는 미들웨어 함수가 된다. next()는 사용하지 않지만 error handling middleware라는 것을 알려주기 위해 명시해야 한다.

 

위 예제는 get 요청시 404에러를 생성한다. 처음으로 등록된 error handling middleware는 404인지 확인하고 맞다면 not found error를, 아니라면 다음으로 넘기고, 두번째 error handling middleware는 아직 header 응답을 보내지 않았다면 unknown error를 보낸다.

이렇게 error handling 미들웨어도 조건과 next를 chaining 할 수 있다.

 

 

 

Third-party middleware

유용하게 사용할 수 있는 써드파티 미들웨어. npm으로 모듈을 설치하고 사용하면 된다.

 

 

 

 

출처

 

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

 

Using Express middleware

Using middleware Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls. Middleware functions are functions that have access to the request ob

expressjs.com

 

Build and Understand Express Middleware through Examples

This tutorial walks you through creating and understanding middleware for Express.

developer.okta.com

 

반응형

관련글 더보기

댓글 영역