라우트 핸들러는 하나의 경로에 여러개의 라우트를 정의할 수 있습니다. 하지만 동일한 메소드를 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를 받아 처리합니다.
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
// load the cookie-parsing middleware
app.use(cookieParser());