Discovery 2. 쿠키는 요청에 자동으로 포함되지 않는다.

CHAEIN·2021년 9월 6일
0

Into the Error

목록 보기
2/3

문제 상황

서버에서 클라이언트 api 요청에 대한 정보를 세션에 in-memory 방식으로 저장하고자 res.session.save()메소드를 사용했다. 문제는 메소드가 동작하지 않고 res.session이 계속 초기화되는 것이었다.

module.exports = {
  post: async (req, res) => {
    const userInfo = await Users.findOne({
      where: { userId: req.body.userId, password: req.body.password },
    });


    if (!userInfo) {
      res.status(400).send({ message: "not authorized" });
    } else {
      req.session.save(function () {
        req.session.userId = userInfo.userId;
        res.send({ data: userInfo, message: "ok" });
      }); // session이 저장되지 않는 문제 발생.
    }
  },
};

해결 방법

문제는 cors 설정에 있었다. cors options으로 credentials: true,를 추가하고 클라이언트 api 요청 헤더에 withCredentials: true를 추가하자 res.session.save()메소드가 정상적으로 동작하고 쿠키 또한 서버에 전달 되었다.

//server

app.use(
  cors({
    origin: "https://localhost:3000",
    methods: ["GET", "POST", "OPTIONS"],
    credentials: true,
  })
);

//client
const handleLogout = (logoutHandler) => {
    axios
      .post("https://localhost:4000/users/logout", null, {
        "Content-Type": "application/json",
        withCredentials: true,
      })
      .then((res) => {
        logoutHandler();
      });
  };

CORS는 다른 origin에 대한 요청을 클라이언트 자체적으로 거부하는 정책인데 이에 서버에서 CORS options을 설정하면 다른 origin에 대한 요청을 설정값에 맞게 수행할 수 있다.

같은 origin에서는 http 통신을 하는 경우 알아서 cookie가 request header에 들어간다. 하지만 origin이 다른 http 통신에서는 request header에 쿠키가 자동으로 들어가지 않는다.request header에 쿠키가 없으면 서버는 클라이언트를 식별할 수 없기 때문에 request header에 쿠키를 담을 수 있도록 따로 설정해주어야 한다.

이때 이 역할을 수행하는게 서버에서는 credentials:true, 클라이언트에서는 withCredentials: true설정이다.

0개의 댓글