주소를 분리하면 공통적인 코드에 대해서 중복이 발생한다.

app.get('/', (req, res) => {
    console.log('모든 요청에 실행하고 싶어요');
    res.send('Hello Express');
})
 
app.post('/', (req, res) => {
    console.log('모든 요청에 실행하고 싶어요');
    res.send('Hello Express');
})
 
app.get('/about', (req, res) => {
    console.log('모든 요청에 실행하고 싶어요');
    res.send('Hello Express');
})

미들웨어

이를 미들웨어로 해결할 수 있다.

미들웨어는 클라이언트의 요청(req)과 서버의 응답(res) 사이에서 특정 로직을 가로채어 처리하는 중간 함수이다.

app.use((req, res, next) => {
    console.log('모든 요청에 실행하고 싶어요');
    next();
})
 
app.get('/', (req, res) => {
    res.send('Hello Express');
})
 
app.post('/', (req, res) => {
    res.send('Hello Express');
})
 
app.get('/about', (req, res) => {
    res.send('Hello Express');
})
app.use((req, res, next) => {
  console.log('모든 요청에 실행하고 싶어요');
  next();
}

express에는 next라는 세 번째 인자가 있는데 해당 매개변수를 직접 실행해줘야, 미들웨어 이후에 일치하는 라우터를 찾아간다.

주의해야 할 점은 일치하는 라우터를 찾아갈 때, 위에서 아래로 간다.

app.get('/category/:name', (req, res) => {
    res.send('hello wildcard');
})
 
app.get('/category/javascript', (req, res) => {
    res.send('hello javascript');
})

이런 코드가 있고 /category/javascript를 호출했다면, 더 fit한 아래 라우터로 찾아갈 거 같지만, 실제로는 와일드카드에 걸린 후 종료된다. Node.js는 위에서 아래로 코드를 읽기 때문에 위 코드에서처럼 범용적인 라우터를 상단에 배치하면 안된다. 따라서 아래처럼 수정해야 한다.

app.get('/category/javascript', (req, res) => {
  res.send('hello javascript');
})
 
// /category로 시작하는 주소
app.get('/category/:name', (req, res) => {
  res.send(`hello ${req.params.name}`);
})
 
// 모든 요청에 대해 처리
app.get('*', (req, res) => {
  res.send('hello everyone');
})

이렇듯 미들웨어는 사용자 인증(로그인 상태 확인), CORS 에러 해결, 클라이언트가 보낸 JSON 데이터 파싱 등을 처리할 때 자주 사용된다.