미들웨어의 중요한 특징

미들웨어 중요한 특징 5가지 ✏️

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import express from 'express'
const app = express();
app.get('/',
(req,res,next)=>{
console.log('first');
next('route'); // 다음 오는 미들웨어를 스킵함
},
(req,res,next)=>{
console.log('first2');
next(new Error('error')); // 에러를 던짐
}
);
app.get('/',(req,res,next)=>{
console.log('second');
});
app.use((req,res,next)=>{
res.status(404).send('Not available!');
}); // 마지막까지 처리할 수 없는 경로로 요청이 들어왔을 경우, 이렇게 404 에러와 함께 메세지를 전달줘야함
app.use((error, req, res, next)=>{
console.error(error);
res.status(500).send('Sorry, try later!');
});
// 어플리케이션 미들웨어 체인의 마지막엔 항상 에러 핸들러를 달아줘야함
app.listen(8080);
import express from 'express' const app = express(); app.get('/', (req,res,next)=>{ console.log('first'); next('route'); // 다음 오는 미들웨어를 스킵함 }, (req,res,next)=>{ console.log('first2'); next(new Error('error')); // 에러를 던짐 } ); app.get('/',(req,res,next)=>{ console.log('second'); }); app.use((req,res,next)=>{ res.status(404).send('Not available!'); }); // 마지막까지 처리할 수 없는 경로로 요청이 들어왔을 경우, 이렇게 404 에러와 함께 메세지를 전달줘야함 app.use((error, req, res, next)=>{ console.error(error); res.status(500).send('Sorry, try later!'); }); // 어플리케이션 미들웨어 체인의 마지막엔 항상 에러 핸들러를 달아줘야함 app.listen(8080);
import express from 'express'
const app = express();

app.get('/',
    (req,res,next)=>{
        console.log('first');
        next('route'); // 다음 오는 미들웨어를 스킵함
    },
    (req,res,next)=>{
        console.log('first2');
        next(new Error('error')); // 에러를 던짐
    }
); 

app.get('/',(req,res,next)=>{
    console.log('second');
}); 

app.use((req,res,next)=>{
    res.status(404).send('Not available!');
}); // 마지막까지 처리할 수 없는 경로로 요청이 들어왔을 경우, 이렇게 404 에러와 함께 메세지를 전달줘야함

app.use((error, req, res, next)=>{
    console.error(error);
    res.status(500).send('Sorry, try later!');
});
// 어플리케이션 미들웨어 체인의 마지막엔 항상 에러 핸들러를 달아줘야함 

app.listen(8080);
  1. 하나의 라우트에 대해서 특정한 처리를 하는 콜백함수를 등록했다면, 동일한 라우트에 대해 등록을 중복으로 할 수 있다.

2. 위 코드처럼 미들웨어는 설정한 순서가 중요하다. 항상 콜백함수 안에서 next()를 이용하여 다음으로 넘어가던지, 아니면 res.send()를 이용하여 처리를 해줘야한다.
단, res 를 이용하여 응답한 경우에는 다른 동일한 경로로 설정한 콜백함수는 실행되지 않는다.

3. 항상 app 미들웨어 체인의 마지막에는 에러 핸들러를 달아주어야한다. 실제 오류에 대한 정보는 console에 남기고, 클라이언트단에는 응답코드 500(서버 오류라면) 와 정의된 오류 내용을 보내주는 것이 좋다. 이렇게 중간중간에 에러가 발생하더라도 맨 마지막에 있는 미들웨어가 에러에 대한 핸들링을 해줄 수 있다.

4. app.all은 어떤 http method로 보내던 항상 등록한 콜백함수가 수행되지만, 경로가 정확히 맞지 않는 경우는 수행되지 않는다. (단 , *을 쓰면 전체 경로에 적용됨)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app.all('/api/*',(req,res,next)=>{
console.log('all');
next();
})
app.all('/api/*',(req,res,next)=>{ console.log('all'); next(); })
app.all('/api/*',(req,res,next)=>{
    console.log('all');
    next();
})

반대로 app.use 의 경우에는 뒤에 이어지는 하위 경로에 대해 콜백함수가 실행된다.
(ex. ‘/’ 에 logger 등록시, / 하위의 모든 경로에 적용됨)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app.use('/api,(req,res,next)=>{
console.log('use');
next();
});
// localhost:8080/api/v1 호출시에도 콜백함수 동작
app.use('/api,(req,res,next)=>{ console.log('use'); next(); }); // localhost:8080/api/v1 호출시에도 콜백함수 동작
app.use('/api,(req,res,next)=>{
    console.log('use');
    next();
});
// localhost:8080/api/v1 호출시에도 콜백함수 동작

5. 클라이언트에게 한번 response를 주면, 다시 보낼 수 없다.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app.get('/',(req,res,next){
if(true){
res.send('hello');
}
res.send('hello again!');
});
// Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 발생
app.get('/',(req,res,next){ if(true){ res.send('hello'); } res.send('hello again!'); }); // Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 발생
app.get('/',(req,res,next){
    if(true){
       res.send('hello');
    }
    res.send('hello again!');
});

// Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 발생

그래서 res.send()를 할때는, return을 붙여 콜백함수가 아예 끝나도록 해주는게 중요하다

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app.get('/',(req,res,next)=>{
if(true){
return res.send('hello'); //return 으로 현재 동작하는 콜백함수를 종료
}
res.send('hello again!');
});
app.get('/',(req,res,next)=>{ if(true){ return res.send('hello'); //return 으로 현재 동작하는 콜백함수를 종료 } res.send('hello again!'); });
app.get('/',(req,res,next)=>{
    if(true){
       return res.send('hello'); //return 으로 현재 동작하는 콜백함수를 종료
    }
    res.send('hello again!');
});