라우트 핸들러는 하나의 경로에 여러개의 라우트를 정의할 수 있습니다. 하지만 동일한 메소드를 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());
# 스키마 생성
CREATE SCHEMA test;
# 사용자 생성 및 권한 추가
CREATE USER 'test'@'localhost' identified with mysql_native_password by 'test';
GRANT ALL PRIVILEGES ON test.* TO 'test'@'localhost';
flush privileges;
# 테이블 생성
CREATE TABLE IF NOT EXISTS `test`.`user` (
`id` INT NOT NULL AUTO_INCREMENT,
`userid` VARCHAR(50) NULL,
`username` VARCHAR(50) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
# 테스트 데이터 입력
insert into test.user(userid, username) values ('codegear', '코드기어');
insert into test.user(userid, username) values ('ironman', '아이언맨');
insert into test.user(userid, username) values ('spiderman', '스파이더맨');
nvm install을 사용해서 새로운 버전의 NodeJS 추가할 수 있습니다. nvm install {버전번호} (nodejs의 특정 버전 설치) nvm install latest (최신버전의 nodejs 설치) nvm install lts (nodejs LTS 버전 설치)