본문 바로가기

LearningJavaScript/Node.js

[express] [미들웨어] [cors] [express-session]

express를 사용해서 서버를 실행하고, cors와 express-session 미들웨어를 추가했다.

 

각각의 미들웨어의 역할과 그 안의 option들도 살펴보려고 한다. (그 동안엔 복붙으로 써왔다. 대충, cors에서 origin은 요청 오리진을 설정해주고, methods는 요청 메소드를 제한해주는 정도로만 알고 있었다. 쿠키-세션도 어능정도 복습이 필요할것 같다..)

 

//server/index.js

const express = require("express");
require("./models");

// TODO : express-session, cors 등 필요한 middleware를 추가하세요.

const mainController = require("./controllers");

const session = require('express-session'); //http://expressjs.com/en/resources/middleware/session.html 참고함
const cors = require('cors'); //https://expressjs.com/en/resources/middleware/cors.html 참고

const app = express();

const port = 4000;

// TODO : express-session, cors 등 필요한 middleware를 적용하세요.

app.use(session({
  secret: 'hello kitty',
  resave: false, //forces the session to be saved back to the session store, even if the session was never modified during the request; typically, you'll want FALSE, though its default value is true
  saveUninitialized: true //Forces a session that is “uninitialized” to be saved to the store.
}));

app.use(cors({
  origin: 'http://localhost:3000', //restricts AJAX access to a single origin
  credentials: true, //when set to true, configures the Access-Control-Allow-Credentials CORS header and passes the header
  methods: 'GET, POST, OPTIONS' //can also be written as ['GET', 'POST', 'OPTIONS']; configures the Access-Control-Allow-Methods CORS header
}));

 

 

Questions or problems to solve:

1. express-session에서 saveUninitialized를 "Choosing false is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie. Choosing false will also help with race conditions where a client makes multiple parallel requests without a session." 라고 하는데, 그럼 지금은 true로 했지만 false가 되야 될것 같다.. 이 친구가 정확히 무얼하는지 알아봐야겠다..

 

stackoverflow에 "When to use saveUnitialized and resave in express-session"라는 나와 비슷한 질문이 역시 있었다. 그래서 답변을 보니, (해석함)

 

더보기

클라이언트가 보내는 HTTP 요청에 session cookie가 없으면, express-session이 새로운 session을 생성해준다고 한다. 그리고 새로운 세션 생성과 함께 다음과 같은 작업도 일어난다.

  • unique한 session id 생성
  • 해당 session id를 session cookie에 저장함으로써 다음 클라이언트 요청을 인식한다
  • req.session(안)에 빈 session 객체 생성
  • saveUninitialized 값에 따라, 요청 마지막에 session객체는, 보통은 데이터베이스에 해당되는, session store에 저장된다

 

session 객체 생명주기가 살아있는 동안에, 세션 객체가 변하지 않고(not modified), 요청 끝에서 saveUninitialized가 false일 때, 바뀌지 않아(not modified) 여전히 빈 객체인 session 객체는 session store에 저장되지 않을 것이다.

 

저장이 되지 않는 이유는, 빈 session 객체들로 하여금 session stored에 (쓸데 없이) 저장되는 것을 방지하기 위해서다.

 

그렇다면, 우리는 언제 저장하면 좋을까? 재방문한 사용자를 알아보고싶을 때, 재방문한 사용자가 해당 사용자의 unique한 id를 갖고 있는 session cookie를 요청에 보냄으로써 인식할 수 있을 것이다.

 

Resave는 "touch" 명령어(command)를 지원하지 않는 session store를 위해 활성화(enabled)돼야 될 것이다. resave는 session store에 특정 세션이 아직 active하다고 말해준다. 그렇지 않으면, 어떤 store는 사용되지 않은 session들을 일정 시간이 지나면 삭제하기때문이다.

 

만약 session store driver가 touch command를 implement하지 않으면, resave를 활성화시켜서 요청 과정에서 session이 저장되지 않더라도 세션을 active하다고 말해줌으로써 store에 update시켜줄 수 있다.

 

따라서 resave 옵션 설정은 완전히 사용하는 session store에 따라 결정하게 된다.

 

그래서 지금 내가 한 설정이 맞는지는 여전히 잘 모르겠다.. 일단 다음 단계로 넘어가서 다시 확인해봐야겠다.

 



 

2. session과 cors의 위치/순서가 does it matter?

 

 

REFERENCES:

Node.js 교과서

CORS

Express-session