# 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="/files/cwZXUALMM5NU7aPu3o2d" 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
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://adam-37.gitbook.io/joomadeung/node.js/node.js-express-mysql/express-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
