const logger = (req,res,next)=>{
console.log(`Request ${req.path}`);
next();
} // next를 사용하지 않으면 middleware가 끊기므로 주의
const auth = (req,res,next)=>{
if(!isAdmin(req)){
res.send('not authorized');
return;
}
next();
}
app.use((req,res,next)=>{
console.log(`${req.path}`);
next();
})
app.use(auth);
app.get('/',(req,res,next)=>{
res.send('heelo express');
})
router.use(auth); //3
router.get('/',(req,res,next)=>{
res.send('hello router');
}) //4
app.use((req,res,next)=>{
console.log(`${req.path}`);
next();
}) // 1
app.use('/admin',router) // 2
app.use(middleware1,middleware2); // 순서대로 동작
app.use('/admin',auth,adminRouter); // 순서대로 동작
app.use((req,res,next)=?{
if(!isAdmin(req)){
next(new Error('not authorized')); // 1. 에러 발생시킴
return;
}
next();
})
app.get('/',(req,res,next)){ // 3. 여기 미들웨어는 실행되지 않음
res.send('nothing')
}
app.use((err,req,res,next)=>{ // 2.바로 여기로 전달됨
res.send('error!!!')
})
auth 함수 실행 시 미들웨어의 동작이 결정되는 방식으로 저장됨
const auth = (memberType)=>{
return (req,res,next)=>{
if(!checkMember(req,memberType)){
next(new Error(`member not ${memberType}`));
return;
}
next();
}
}
app.use('/admin',auth('admin'),adminRouter);
app.use('/admin',auth('member'),userRouter);
app.use((req, res, next) => {
// app 객체 내부 함수는 미들웨어, use는 모든 요청에 실행하고 싶을 때 사용
console.log('모든 요청에 실행');
next();
});
////
app.use('/about', (req, res, next) => {
// use에 주소를 붙이면 about에서만 실행됨
console.log('모든 요청에 실행');
next();
});
////
app.use(
// app 객체 하나에 여러개의 미들웨어가 있어도 됨
(req, res, next) => {
console.log('모든 요청에 실행');
next();
},
(req, res, next) => {
console.log('모든 요청에 실행');
next();
},
(req, res, next) => {
console.log('모든 요청에 실행');
next();
}
);
////
app.use((req, res, next) => {
// 기본적으로 상태코드 200 생략되어 있음
res.status(200).send('hi');
});
////
app.get('/', (req, res) => {
// 한 요청(이전 미들웨어도 포함)에 에서 두 번이상 response하면 에러나옴
res.sendFile(path.join(__dirname, 'index.html'));
res.json();
res.send('hi');
});
////
app.get('/', (req, res) => {
// 기존 http에서는 아래와 같이 표기
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('hi');
// express에서는 header도 더 간편하게 표기
res.setHeader('Content-Type', 'text/html');
// express에서는 http의 두 줄을 아래 한 줄로 표기
res.status(200).send('안녕하세요'); //status 생략가능
});