axios 요청 후 accessToken과 refreshToken이 undefined일 때

Song·2022년 5월 11일
1
post-thumbnail

서버와 요청을 주고받다보면 헤더설정이나 권한설정을 잘못할 경우 값을 제대로 불러오지 못하는 경우가 종종 있다.
분명 로그인하고 나서 서버로부터 accessToken을 받아오고, refreshToken을 쿠키에 저장하도록 했는데도,
다시 토큰을 가지고 서버로 요청할때 서버에서 토큰 값을 undefined로 인식하고 있지 못한다면??

내가 어떻게 응답을 보내주고 있는지를 먼저 확인해봐야 한다. 어떤식으로 응답을 보냈고, 어떤 오류를 마주했었는지를 적어보려 한다.

1) 첫번째 시도

요청 코드 >

const handleGetUserInfo = () => {
        console.log(accessToken);
        axios.get(`${REACT_APP_API_URL}/user`,
            {
                headers: {
                    "Content-Type": "application/json",
                    authorization: `Bearer ${accessToken}`,
                }
            }).then((result) => {
                console.log(result.data.data.userInfo);
            })

    }

응답 결과 > 요청헤더에 accessToken은 문제없이 들어가는걸 확인해볼 수 있는데, 어째서인지 cookie값이 인식되지 않는다.

서버 반응 > 둘다 undefined로 나온다.

사실 원래대로라면 콘솔에 accessToken이 찍혀있어야하는데(refreshToken만 없는거니까!) 여기서 undefined가 나온 이유는 console.log(req.header.authorization);로 콘솔을 확인 했기 때문이다....console.log(req.headers.authorization);로 확인하도록! 오타 주의~

바보갓은 나에모습,,

어쨌든 첫번째 시도는 refreshToken이 들어오지 않고 있다.

2) 두번째 시도

요청 코드 > refreshToken을 읽어오지 못한다는 것은 https 연결에서 withCredentials 조건이 제대로 설정되지 않았기 때문이다. 그래서 해당 조건을 만족하는 코드를 한줄 추가해줬다.
axios 공식문서를 확인해보니 get요청을 보낼 때 url다음으로 오게 되는 값은 config로 처리해준다. 해당 config에서도 Credential를 사용해 cross-site Access-Control 요청을 보내도록하면 cookie에 들어있는 refreshToken을 불러올 수 있게 되는 것이다.

// `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default
const handleGetUserInfo = () => {
        console.log(accessToken);
        axios.get(`${REACT_APP_API_URL}/user`,
            {
                "Content-Type": "application/json",
                authorization: `Bearer ${accessToken}`,
          //refreshToken을 위해서 필요한 설정!!
                withCredentials: true

            }).then((result) => {
                console.log(result.data.data.userInfo);
            })

    }

응답 결과 > refreshToken이 쿠키에 잘 들어가 요청을 보내주고 있는 것을 확인할 수 있다.

하지만 어째서인지 accessToken은 인식하고 있지 못하는 상황 ㅠ

서버 반응 > 서버의 콘솔에서도 refreshToken은 있는데, accessToken은 undefined로 보여주고 있다.


3) 최종 요청 성공

요청 코드 >
마찬가지로 axios요청 공식문서에 기재되어 있는 걸 참고해보았다. 알고보니 헤더설정은 따로 커스텀한 헤더를 넣게될 경우 config안에서도 headers라는 키값으로 가지고 있어야 했다.

// `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},

헤더설정을 해주고, withCredentials는 따로 config안에 담은채로 요청을 보낸다.

 const handleGetUserInfo = () => {
        axios.get(`${REACT_APP_API_URL}/user`,
            {
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${accessToken}`,
                },
                withCredentials: true
            }

        ).then((result) => {
            console.log(result.data.data.userInfo);
        })

    }

서버 반응 >
서버에서 토큰을 두개 전부 다 성공적으로 읽는 것을 확인할 수 있다.

응답결과>
마찬가지로 authorization 헤더값에 accessToken이 들어가있고 cookie에도 refreshToken이 잘 담겨진 채로 요청을 보내고 있는 걸 확인할 수 있다.

axios를 사용하는데 어째서인지 토큰값을 인지하지 못하고 있는 상황이라면 네트워크 탭에서 request headers와 서버에서 받아오는 값들을 자세히 비교해보면서, 헤더설정과 config설정을 주의깊게 확인하여 보내도록 하자!!

0개의 댓글