Trouble Shooting

서버에 요청 시 쿠키 함께 전송하기 + cors 오류 해결

SH_Roh 2022. 7. 31. 20:56
반응형

 Problem 1. 

로그인 토큰을 쿠키에 저장하고, 서버에서는 그 토큰을 이용해 login validation을 하고 있었다.

그런데 이미 로그인을 해서 쿠키에 토큰이 있는데도 로그인 정보가 없다고 뜨는 문제가 발생했다.

 

 withCredentials 옵션 추가 

axios.get(`${SERVER_URL}/${endpoint}`, {
  withCredentials: true,
});

 

표준 cors 요청은 기본적으로 쿠키를 설정하거나 보낼 수 없기 때문에 withCredentials부분을 true로 설정해 수동으로 cors 요청에 쿠키값을 넣어줘야 한다.

 

 Problem 2.

이제 쿠키는 잘 전송되는데 cors 오류가 발생했다.

 

 

 서버에서 credentials 옵션 설정하기 

서버에서도 withCredentials 옵션을 설정해줘야 한다.

import cors from 'cors';
import express from 'express';

const app = express();

const corsConfig = {
  origin: true,
  credentials: true,
};

app.use(cors(corsConfig));
app.options('*', cors(corsConfig));

 

말끔하게 해결 완료 ^_^V

반응형