# express 미들웨어

```jsx
// 미들웨어
// 공통되는 코드
app.use((req, res, next) => {
  console.log('모든 요청에 실행하고 싶어요');
  next(); // 넣어줘야 다음 라우터를 찾아 실행함.
});
```

라우팅 매개변수

* 매개변수 라우터는 순서를 지켜줘야 한다.

```jsx
app.get('/category/:name', (req, res) => {
  console.log('res', res);
  console.log('req', req.params);
  res.send(`hello ${req.params.name}`);
});
```

* 만약 매개변수 라우터를 상단에 배치한다면, 그 아래 라우터는 실행이 안된다.

```jsx
app.get('/category/:name', (req, res) => {
  res.send(`hello ${req.params.name}`);
});

// 실행 안됨
app.get('/category/javascript', (req, res) => {
  res.send('hello javascript');
});
```

* 범위가 넓은 라우터들은 다른 라우터들보다 아래에 위치해야한다.

```jsx
// 정상작동
app.get('/category/javascript', (req, res) => {
  res.send('hello javascript');
});

// 매갸변수 라우팅 아래에
app.get('/category/:name', (req, res) => {
  res.send(`hello ${req.params.name}`);
  // res.send(`hello wildcard`);
});

// 범위가 넓은 라우터는 맨 아래에
app.get('*', (req, res) => {
  res.send('hello everybody')
})
```

* 특정 라우터에만 middleware를 실행되게 하고 싶다면,

```jsx
// about에서만 실행됨 그리고 about을 next로 찾아감
app.use('/about', (req, res, next) => {
  console.log('/about에서만 실행하고 싶어요');
  next(); // 그리고나서 /about을 찾아감
});
```

* middleware를 여러개 넣을 수 있다.

```jsx
// 미들웨어
// 공통되는 코드
app.use(
  (req, res, next) => {
    console.log('1 모든 요청에 실행하고 싶어요');
    next();
  },
  (req, res, next) => {
    console.log('2 모든 요청에 실행하고 싶어요');
    next();
  },
  (req, res, next) => {
    console.log('3 모든 요청에 실행하고 싶어요');
    next();
  },
  (req, res, next) => {
    console.log('4 모든 요청에 실행하고 싶어요');
    next();
  }
);

// express server start!!
// 1 모든 요청에 실행하고 싶어요
// 2 모든 요청에 실행하고 싶어요
// 3 모든 요청에 실행하고 싶어요
// 4 모든 요청에 실행하고 싶어요
```

* 미들웨어 에러처리

```jsx
app.use(
  (req, res, next) => {
    console.log('1 모든 요청에 실행하고 싶어요');
    next();
  },
  (req, res, next) => {
    throw new Error('에러가 났어요.');
  }
);
```

<figure><img src="https://4260850757-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbYcvv7IylJ9jaNhqGBno%2Fuploads%2FYqWYvnXvVNccCEqFSMoJ%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202023-05-15%20%E1%84%8B%E1%85%A9%E1%84%92%E1%85%AE%207.39.55.png?alt=media&#x26;token=231bbb76-6e79-4d07-9815-edf4cb2b8f55" alt=""><figcaption></figcaption></figure>

* 에러 미들웨어 에러처리
  * 에러 미들웨어(err, req, res, next)는 인자 4개를 반드시 넣어줘야한다.

```jsx
app.use((err, req, res, next) => {
  console.error(err);
  res.send('에러났습니다!!!!!!!!!!!!!!!!!!!!!!!');
});
```

* 404처리

```jsx
app.use((req, res, next) => {
  res.send('404입니다.')
})
```

* 한 라우터에서 여러번 send를 보내면 에러가 난다.

```jsx
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
  res.send('안녕하세요');
  res.json({ hello: '123' });
});
```

```jsx
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
```
