본문 바로가기
JavaScript/ETC

[Javascript] axios로 rest api 호출시 cookie 값 전달 안되는문제 해결

by 놀러와요 2024. 4. 9.
반응형

Vue나 react로 frontend를 개발하고 spring으로 backend를 개발할 경우 보통은 frontend server와 backend server의 origin이 달라지게 된다.

 

즉 frontend 주소는

localhost:3000

 

backend의 주소는

localhost:8080 이런 식이다.

 

backend side에서 CORS 설정을 해줌으로서 origin이 달라지는 경우에 교차 접근 허용을 설정하여 동작을 진행하게 된다.

 

하지만 origin이 달라지는 경우 분명 browser에서는 cookie값이 확인이 되는데 backend에서 api 호출을 잡아보면 request객체에 cookie값이 안실려오는 경우가 있다.

 

이럴 경우에는 axios 호출시 config에 withCredentials : true 설정을 해주어야 한다.

withCredentials: true

 

간단한 실습 예제를 보자. 아래와 같이 axios를 호출하고 config에는 withCredentials 설정을 생략하여 보자.

post (url, body, success, fail = err => err.response.data.message, config) {
  axios.post(wrap(url), body, appendAuth(config))
    .then(handler.handle(success))
    .catch(fail)
},


const appendAuth = (config) => {
  const token = store.getters.token
  if (token) {
    if (!config) config = { headers: {} }
    if (!config.headers) config.headers = {}
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }

  return config
}

 

간단한 웹 어플리케이션에서 로그인을 한 후 cookie에 refresh_token을 담은 경우를 살펴보자. api 호출전에 아래와 같이 cookie가 생성되어  있음을 알 수 있다.

 

이후 브라우저를 통해 아무 url을 접근해보고 backend쪽 filter에서 break를 잡아서 request 객체의 cookie를 뽑아본다.

아래와 같이 브라우저에서 확인한 refresh_token cookie가 null로 읽히는 것을 볼 수 있다.

 

이번에는 config설정 부분에 withCredentials: true를 추가해본다.

const appendAuth = (config) => {
  const token = store.getters.token
  if (token) {
    if (!config) config = { headers: {} }
    if (!config.headers) config.headers = {}
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  
  // axios config에 withCredentials: true 옵션을 추가한다.
  config = {...config, withCredentials: true}
  return config
}

 

axios에 withCredentials: true를 추가하고 api를 호출하여 보면 request 객체에 cookie값이 정상적으로 실려옴을 확인할 수 있다.

 

반응형