동적 파라미터
쉽게 말해 언제든지 변할수 있는 값을 말함.
app.get('/usr/:dynamic',[callback]);
입력 예시 :
/user/1111
/user/aaaaa
파라미터 값 얻기
req.params.dynamic
연속으로 사용가능
app.get('/usr/:dynamic1/dynamic2',[callback]);
동적 파라미터는 가장 밑으로 넣기
다음 오는 파라미터가 동적 파리미터에
영향을 미쳐 제대로 작동이 안됨
/a/:a
/a/b
이렇게 하면
/a/b b가 :b 처럼 동적파라미터로 인식함
여러가지 라우팅 법
// /abcd, /acd
app.get('/ab?cd', function(req, res) {})
// /abcd, /abbcd, /abbbcd
app.get('/ab+cd', function(req, res) {})
// abcd, abxcd, abRABDOMcd, ab123cd
app.get('/ab*cd', function(req, res) {})
// /abe, /abcde
app.get('/ab(cd)?e', function(req, res) {})
// 정석 방법
app.route(‘/book')
.get(function(req, res) {
res.send('Get a random book');
})
.post(function(req, res) {
res.send('Add a book');
})
.put(function(req, res) {
res.send('Update the book');
});
// 모듈형식으로 분리 방법
let express = require(‘expres’);
let router = express.Router();
router.get('/hello', sayHello);
router.get('/howAreYou/:who', sayThankYou);
module.exports = router;
상대경로 처리 라우터
// /A/B 경로의 요청
app.use('/A', require('./greetingRouter’));
greetingRouter 의 라우팅 코드
router.get('/B', sayHello);
에러 처리 미들웨어는 가장 나중에 배치
// 에러를 단순히 반환하는 방법
app.use(function(err, req, res, next) {
res.status(500).send(‘에러 발생!'); });
// 에러를 미들웨어로 전달하는 방법
app.use((req, res, next)=>{
let error = new Error('에러 메세지')
error.code = 100;
return next(error);
});
환경 설정해서
환경 별로 에러를 다르게
처리할 수 있음
// 환경 저장
// Window - 서비스 환경
set NODE_ENV=product
node myapp.js
// LINUX - 개발 환경
$ NODE_ENV=product node myapp.js
$ NODE_ENV=development node myapp.js
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.end(err.stack);
});
}
else {
app.use(function(err, req, res, next) {
res.status(err.code || 500);
res.end('잠시 후 다시 시도해주세요');
});
}
// 환경별 에러처리 실행
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.end(err.stack);
});
}
else {
app.use(function(err, req, res, next) {
res.status(err.code || 500);
res.end('잠시 후 다시 시도해주세요');
});
}
3자 미들웨어
파피콘
미들웨어중 우선순위가 가장 높음
favicon(path, options)
path : 파비콘 경로
log 남기는 미들웨어
파피콘 다음으로 우선순위 높음
morgan : 간단한 로그
winston : 로그를 저장하고, 디테일하게 수정 가능
(기능을 확장하고 싶다면 추가 모듈 설치 필요)
별도 설치 Transports
- DailyRotateFile
-CouchDB, Redis, MongoDB
- Mail transport
-Notification Service(Amazon SNS)
검색
npm search winston
미들웨어는 기본 3개의 인자를 가지고 있음
const test = (req, res, next) =>{}
그러나 에러 미들웨어는
기본 4개임
const test = (err, req, res, next) =>{}
728x90
반응형