미들웨어는 HTTP 요청과 응답 사이에서 단계별 동작을 수행해주는 함수
req req next를 인자로 갖는 함수를 작성하면 미들웨어가 된다
req, req객체를 통해 HTTP 요청과 응답을 처리하거나 next함수를 통해 다음 미들웨어를 호출해야 함
=> next함수가 호출되지 않으면 미들웨어 싸이클이 멈춘다
const logger = (req, res, next) =>{
console.log(`Request ${req.path}`);
next();
const auth = (req, res, next) => {
if(!isAdmin(req)) {
next(new Error('Not Authorized'));
return;
}
next();
}
use나 http method 함수를 사용하여 미들웨어를 연결할 수 있음
HTTP 요청이 들어온 순간부터 적용된 순서대로 동작
app.use((req, res, next) =>{
console.log(`Request ${req.path}`);
next(); // 1번째 실행
});
app.use(auth); // 2번째 실행
app.get('/', (req, res, next) =>{
res.send('Hello World'); // 3번째 실행
})
특정 경로의 라우팅에만 미들웨어를 적용하기 위한 방법
사용방법은 어플리케이션 미들웨어와 같다
app 객체에 라우터가 적용된 이후로 순서대로 동작함
router.use(auth); // 3번째 실행
router.get('/', (req, res, next) =>{
res.send('Hello Router');
}); // 4번째 실행
app.use((req, res, next) =>{
console.log(`Request ${req.path}`);
next(); // 1번째 실행
});
app.use('/admin, router); // 2번째 실행
일반적으로 가장 마지막에 위치하는 미들웨어로 err, req, res, next 네 가지의 인자를 가진다.
이전에 적용된 미들웨어 중 next에 인자를 넘기는 경우 중간 미들웨어들은 뛰어넘고 오류처리 미들웨어가 바로 실행됨
app.use((req, res, next) =>{
if(!isAdmin(req)) {
next(newError('Not Authorized')); //1. next에 인자를 넘김
return;
}
next();
});
app.get('/', (req, res, next) =>{
res.send('Hello Express');
});
app.use((err, req, res, next) =>{ // 2. 바로 오류처리 미들웨어 실행
res.send('Error Occurred');
});
일반적으로 동일한 로직에 설정값만 다르게 미들웨어를 사용하고 싶을 경우에 활용
const auth = (memberType) =>{
return(req, res, next) =>{
if(!checkMember(req, memberType)) {
next(newError(`member not ${memberType}`));
return;
}
next();
}
}
app.use('/admin', auth('admin'), adminRouter);
app.use('/users', auth('member'), userRouter);