Middleware function 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.
미들웨어 함수란?
미들웨어 함수는 req(요청), res(응답) 객체를 받아 변형할 수 있고 next( ) 함수 호출을 통해 그 다음 미들웨어의 실행여부를 그 이전의 미들웨어가 결정하도록 한다. 또한 특정 경로에 미들웨어 설정하는것을 통해 특정 미들웨어가 동작하도록 설정이 가능하다. 아래의 경우, 해당 경로로 접근하는 모든 종류의 HTTP request에 대해 미들웨어 함수가 실행된다.
app.use('/user/:id', (req, res, next) => {
console.log('Request Type:', req.method)
next();
})
특정 method를 설정하여 해당 method인 경우에만 미들웨어가 동작할 수 있도록 할 수 있다
app.get('/user/:id', (req, res, next) => {
res.send('USER');
})
함수를 인자에 여러개 주는 것을 통해 미들웨어 여러개를 붙여 사용할 수 있다.
app.use('/user/:id', (req, res, next) => {
console.log('Request URL:', req.originalUrl);
next(); //다음 미들웨어 함수를 실행
}, (req, res, next) => {
console.log('Request Type:', req.method);
next();
})
동일한 route에 여러개의 미들웨어가 등록되어있는 경우, 미들웨어 함수의 실행은 다음과 같다.
app.get('/user/:id', (req, res, next) => {
console.log('ID:', req.params.id) // 첫번째로 호출
next();
}, (req, res, next) => {
res.send('User Info') // 두번째로 호출 (next를 호출하지 않으면 이곳에서 종료)
})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', (req, res, next) => {
res.send(req.params.id);
})
조건문을 통해 다음 미들웨어의 실행여부를 결정할 수 있다.
app.get('/user/:id', (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() //인자가 없는 next 이기때문에 바로 아래 미들웨어 함수가 실행
}, (req, res, next) => {
// send a regular response
res.send('regular');
})
// handler for the /user/:id path, which sends a special response
app.get('/user/:id', (req, res, next) => {
res.send('special');
})
what is next( ) ?
next 함수는 Express 라우터에서 사용되는 함수로 호출이 되면 현재 미들웨어의 다음으로 오는 미들웨어를 실행시킨다.
미들웨어 함수의 역할
- 모든 코드를 실행
- request, response 객체에 대한 변경
- request, response cycle 종료
- 스택내의 다음 미들웨어 호출
현재 미들웨어 함수가 request, response cycle을 종료하지 않으면 next 함수를 호출하여 그 다음 미들웨어 함수에 제어권을 전달한다 그렇지 않을 경우 해당 요청은 정지된다(진행되지 않는다.) 미들웨어의 로드 순서는 매우 중요하며 먼저 로드되는 미들웨어 함수가 먼저 실행된다.
const express = require('express');
const app = express();
const myLogger = function (req, res, next) {
console.log('LOGGED');
next();
};
app.use(myLogger); // 콘솔창에 'LOGGED'가 찍힌후,
app.get('/', function (req, res) {
res.send('Hello World!'); //브라우저 화면에 'Hello World!' 출력!
});
app.listen(3000);
/*
!! 만약 루트 경로("/")에 대한 라우팅 이후에 myLogger가 로드되면,
루트 경로의 라우트 핸들러가 req-res cycle을 종료하므로 요청은 절대로 myLogger에
도달하지 못하므로 콘솔창에 'LOGGED' 출력되지 않는다
*/
Reference
'BACKEND' 카테고리의 다른 글
Node.js와 Express.js (0) | 2022.08.19 |
---|---|
[Express.js] res.json vs res.send vs res.end (0) | 2022.08.19 |
[Express.js] 에러 핸들링 (0) | 2022.08.19 |