> For the complete documentation index, see [llms.txt](https://adam-37.gitbook.io/joomadeung/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adam-37.gitbook.io/joomadeung/node.js/node.js-express-mysql/morgan-cookie-parser-express-session.md).

# morgan / cookie-parser / express-session

* dependencies 추가

```bash
$ yarn add morgan cookie-parser express-session
```

* morgan 불러오기 및 적용

```jsx
const morgan = require('morgan');

app.use(morgan('dev'));
app.use(morgan('combined')) // 실제 배포에서 사용, 더 자세히 보여줌
```

<figure><img src="/files/UITJSHuWYHdV6FWkerVT" alt=""><figcaption></figcaption></figure>

client에서 어떤 요청이 왔는지 server에 기록된다.

요청과 응답을 기록하는 라우터: morgan

<figure><img src="/files/G74ulGqrrqfHFPd4km25" alt=""><figcaption></figcaption></figure>

### cookie-parser

**http의 cookie 설정**

```jsx
res.writeHead(302, {
      Location: '/',
      'Set-Cookie': `name=${encodeURIComponent(name)}; Expires=${expires.toGMTString()}; HttpOnly; Path=/`,
    });
```

**express의 cookie 설정**

```jsx
const cookieParser = require('cookie-parser');
app.use(cookieParser());

// app.get('/') 미들웨어에 아래와 같이 삽입

		req.cookies; // { mycookie: 'test'}

    // 쿠키 설정
    res.cookie('name', encodeURIComponent(name), {
      expires: new Date(),
      httpOnly: true,
      path: '/',
    });

    // 쿠키 삭제
    res.clearCookie('name', encodeURIComponent(name), {
      httpOnly: true,
      path: '/',
    });
```

성형된 cookie를 사용하려면?

```jsx
app.use(cookieParser('testpassword'));

req.signedCookies
```

### express에서 기본으로 장착된 body-parser의 기능

```jsx
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
```

* **express.json()**
  * Content-Type: application/json으로 전송된 요청(client에서 json data를 보냈을때) 본문(body)을 처리하는 데 사용. JSON 데이터를 JavaScript 객체로 파싱하고, 이를 req.body 속성에 할당하여 다음 처리 단계에서 사용할 수 있도록 한다.
* **urlencoded()**
  * client에서 form을 submit할 때 기본적으로 urlencoded이다. 이 form을 parsing.
  * extended 옵션을 true로 설정하면 복잡한 객체와 배열도 파싱 (true면 qs, false면 querystring)
