# static / express-session

### static

* 정적 파일을 제공하기 위해 사용되는 미들웨어

사용방법

```jsx
app.use(express.static(path.join(__dirname, 'public-3030')));
```

* 현재 스크립트 파일이 위치한 폴더 경로에 'public-3030'이라는 폴더가 있다고 가정하고 해당 폴더에 정적 파일이 위치하고 있으므로, 이 폴더를 정적 파일 제공을 위한 디렉토리로 설정
* 예를 들어, <http://localhost:3000/index.html> 요청이 오면, 위에서 설정한 'public-3030' 폴더에서 index.html 파일을 찾아 응답으로 보내주게 됩니다. 마찬가지로, 이미지 파일이나 스타일시트 등 다른 정적 파일에 대해서도 마찬가지로 응답으로 제공
* 정적 파일을 쉽게 제공할 수 있으므로, HTML, CSS, JavaScript 등의 파일들을 적절하게 관리 가능

### express-session

* 요청마다 개인의 저장공간을 만들어주는게 express-session

```jsx
const session = require('express-session');

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

app.use(
  session({
    resave: false,
    saveUninitialized: false,
    secret: 'adampassword', // cookie-parsser의 password와 같이 작성
    cookie: {
      httpOnly: true,
    },
    name: 'connect.sid', // 기본값, 클라이언트에 저장되는 세션 쿠키는 'connect.sid'라는 이름을 가지게 됨
  })
);

app.get('/', (req, res, next) => {
	req.session;
})
```

사용방법

* app.use를 사용해서 앱에 등록
* session의 옵션들
  * **`secret`**: 세션을 암호화하기 위한 비밀 키. 이 값을 설정하지 않으면 세션을 제대로 암호화하지 못하므로 보안상 매우 중요
  * **`resave`**: 변경 사항이 없더라도 세션을 항상 저장할지 여부를 지정. 이 값을 \*\*`false`\*\*로 설정하면 변경 사항이 없는 경우에도 세션을 저장하지 않으므로, 성능을 높임
  * **`saveUninitialized`**: 초기화되지 않은 새로운 세션을 저장할지 여부를 지정. 이 값을 \*\*`true`\*\*로 설정하면 초기화되지 않은 새로운 세션을 저장.

### data

* 라우터에서 다른 라우터로 data를 보내고 싶을때?
  * session에 저장하면 다음 요청때도 data가 남아있음

```jsx
app.use((req, res, next) => {
  req.session.data = 'adam비번';
});

app.get('/', (req, res, next) => {
  req.session.data; // adam비번

  res.send('./index.html');
  console.log('123');
});
```

* 1회성으로만 남기고 싶다면

```jsx
app.use((req, res, next) => {
  req.data = 'adam비번';
});

app.get('/', (req, res, next) => {
  req.data; // adam비번

  res.send('./index.html');
  console.log('123');
});
```


---

# 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/static-express-session.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.
